How do you print rows and columns in python?

Hello, readers! In this article, we will be focusing on different ways to print column names in Python.

So, let us get started!


First, where do you find columns in Python?

We often come across questions and problem statements wherein we feel the need to deal with data in an excel or csv file i.e. in the form of rows and columns.

Python, as a programming language, provides us with a data structure called ‘DataFrame’ to deal with rows and columns.

A Python DataFrame consists of rows and columns and the Pandas module offers us various functions to manipulate and deal with the data occupied within these rows and columns.

Today, we will be having a look at the various different ways through which we can fetch and display the column header/names of a dataframe or a csv file.

We would be referring the below csv file in the below examples–

How do you print rows and columns in python?
Dataset-Bank Loan


1. Using pandas.dataframe.columns to print column names in Python

We can use pandas.dataframe.columns variable to print the column tags or headers at ease. Have a look at the below syntax!

Example:

import pandas

file = pandas.read_csv("D:/Edwisor_Project - Loan_Defaulter/bank-loan.csv")
for col in file.columns:
    print(col)

In this example, we have loaded the csv file into the environment. Further, we have printed the column names through a for loop using dataframe.columns variable.

Output:

age
ed
employ
address
income
debtinc
creddebt
othdebt
default


2. Using pandas.dataframe.columns.values

Python provides us with pandas.dataframe.columns.values to extract the column names from the dataframe or csv file and print them.

Syntax:

Example:

import pandas

file = pandas.read_csv("D:/Edwisor_Project - Loan_Defaulter/bank-loan.csv")
print(file.columns.values)

So, the data.columns.values gives us a list of column names/headers present in the dataframe.

Output:

['age' 'ed' 'employ' 'address' 'income' 'debtinc' 'creddebt' 'othdebt' 'default']


3. Python sorted() method to get the column names

Python sorted() method can be used to get the list of column names of a dataframe in an ascending order of columns.

Have a look at the below syntax!

Syntax:

Example:

import pandas

file = pandas.read_csv("D:/Edwisor_Project - Loan_Defaulter/bank-loan.csv")
print(sorted(file))

Output:

['address', 'age', 'creddebt', 'debtinc', 'default', 'ed', 'employ', 'income', 'othdebt']


Conclusion

By this, we have come to the end of this topic. Hope this article turns out to be a hack for you in terms of different solutions for a single problem statement.

For more such posts related to Python, Stay tuned and till then, Happy Learning!! 🙂

A Data frame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows and columns. We can perform basic operations on rows/columns like selecting, deleting, adding, and renaming. In this article, we are using nba.csv file.

How do you print rows and columns in python?

Dealing with Columns

In order to deal with columns, we perform basic operations on columns like selecting, deleting, adding and renaming.

How do you print rows and columns in python?

Column Selection:
In Order to select a column in Pandas DataFrame, we can either access the columns by calling them by their columns name.

import pandas as pd

data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'],

        'Age':[27, 24, 22, 32],

        'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj'],

        'Qualification':['Msc', 'MA', 'MCA', 'Phd']}

df = pd.DataFrame(data)

print(df[['Name', 'Qualification']])

Output:

How do you print rows and columns in python?

For more examples refer to How to select multiple columns in a pandas dataframe
 
Column Addition:
In Order to add a column in Pandas DataFrame, we can declare a new list as a column and add to a existing Dataframe.

import pandas as pd

data = {'Name': ['Jai', 'Princi', 'Gaurav', 'Anuj'],

        'Height': [5.1, 6.2, 5.1, 5.2],

        'Qualification': ['Msc', 'MA', 'Msc', 'Msc']}

df = pd.DataFrame(data)

address = ['Delhi', 'Bangalore', 'Chennai', 'Patna']

df['Address'] = address

print(df)

Output:

How do you print rows and columns in python?

For more examples refer to Adding new column to existing DataFrame in Pandas
 
Column Deletion:
In Order to delete a column in Pandas DataFrame, we can use the drop() method. Columns is deleted by dropping columns with column names.

import pandas as pd

data = pd.read_csv("nba.csv", index_col ="Name" )

data.drop(["Team", "Weight"], axis = 1, inplace = True)

print(data)

Output:
As shown in the output images, the new output doesn’t have the passed columns. Those values were dropped since axis was set equal to 1 and the changes were made in the original data frame since inplace was True.

Data Frame before Dropping Columns-

How do you print rows and columns in python?


Data Frame after Dropping Columns-
How do you print rows and columns in python?

For more examples refer to Delete columns from DataFrame using Pandas.drop()

Dealing with Rows:

In order to deal with rows, we can perform basic operations on rows like selecting, deleting, adding and renaming.

Row Selection:
Pandas provide a unique method to retrieve rows from a Data frame.DataFrame.loc[] method is used to retrieve rows from Pandas DataFrame. Rows can also be selected by passing integer location to an iloc[] function.

import pandas as pd

data = pd.read_csv("nba.csv", index_col ="Name")

first = data.loc["Avery Bradley"]

second = data.loc["R.J. Hunter"]

print(first, "\n\n\n", second)

Output:
As shown in the output image, two series were returned since there was only one parameter both of the times.

How do you print rows and columns in python?

For more examples refer to Pandas Extracting rows using .loc[]
 
Row Addition:
In Order to add a Row in Pandas DataFrame, we can concat the old dataframe with new one.

import pandas as pd 

df = pd.read_csv("nba.csv", index_col ="Name"

df.head(10)

new_row = pd.DataFrame({'Name':'Geeks', 'Team':'Boston', 'Number':3,

                        'Position':'PG', 'Age':33, 'Height':'6-2',

                        'Weight':189, 'College':'MIT', 'Salary':99999},

                                                            index =[0])

df = pd.concat([new_row, df]).reset_index(drop = True)

df.head(5)

Output:

Data Frame before Adding Row-

How do you print rows and columns in python?


Data Frame after Adding Row-
How do you print rows and columns in python?


For more examples refer to Add a row at top in pandas DataFrame
 
Row Deletion:
In Order to delete a row in Pandas DataFrame, we can use the drop() method. Rows is deleted by dropping Rows by index label.

import pandas as pd

data = pd.read_csv("nba.csv", index_col ="Name" )

data.drop(["Avery Bradley", "John Holland", "R.J. Hunter",

                            "R.J. Hunter"], inplace = True)

data

Output:
As shown in the output images, the new output doesn’t have the passed values. Those values were dropped and the changes were made in the original data frame since inplace was True.

Data Frame before Dropping values-

How do you print rows and columns in python?


Data Frame after Dropping values-
How do you print rows and columns in python?

For more examples refer to Delete rows from DataFrame using Pandas.drop()
 
Problem related to Columns:

  • How to get column names in Pandas dataframe
  • How to rename columns in Pandas DataFrame
  • How to drop one or multiple columns in Pandas Dataframe
  • Get unique values from a column in Pandas DataFrame
  • How to lowercase column names in Pandas dataframe
  • Apply uppercase to a column in Pandas dataframe
  • Capitalize first letter of a column in Pandas dataframe
  • Get n-largest values from a particular column in Pandas DataFrame
  • Get n-smallest values from a particular column in Pandas DataFrame
  • Convert a column to row name/index in Pandas

Problem related to Rows:

  • Apply function to every row in a Pandas DataFrame
  • How to get rows names in Pandas dataframe

How do you print columns and rows in Python?

3 Easy Ways to Print column Names in Python.
Using pandas. dataframe. columns to print column names in Python. ... .
Using pandas. dataframe. columns. ... .
Python sorted() method to get the column names. Python sorted() method can be used to get the list of column names of a dataframe in an ascending order of columns..

How do you print a row in Python?

To print on the same line in Python, add a second argument, end=' ', to the print() function call. print("It's me.")

How do I show the first 10 rows in Python?

Use pandas. DataFrame. head(n) to get the first n rows of the DataFrame. It takes one optional argument n (number of rows you want to get from the start).

How do you print a column of output in Python?

Print With Column Alignment in Python.
Use the % Formatting to Print With Column Alignment in Python..
Use the format() Function to Print With Column Alignment in Python..
Use f-strings to Print With Column Alignment in Python..
Use the expandtabs() Function to Print With Column Alignment in Python..