The best way to get column labels in a Information Body
Pandas Information Body has the columns property that you could be use to get the column labels in an information body.
Syntax:
DataFrame.columns
Within the instance beneath, we’ll present you getting column labels of information frames which are created based mostly on CSV and Excel recordsdata.
An instance to get column labels of a CSV file
Within the instance beneath, we’ll load a CSV file through the use of the read_csv technique of Pandas.
Our pattern CSV file is proven beneath:
That is used to create an information body.
That is adopted through the use of the columns property of the DF to show the column labels within the CSV file:
Code:
|
import pandas as pd
#Specifying CSV file
df = pd.read_csv(‘pandas_csv.csv’)
#Show column labels
print(df.columns) |
Output:
Index([‘Product ID’, ‘Product Name’, ‘Price’, ‘Status’], dtype=’object’)
The instance of utilizing an excel file and displaying its columns
This time, an information body is created through the use of the read_excel technique of Padnas.
Pattern Excel sheet:
Then columns property of the Information Body is used to show the labels within the knowledge body.
Python program:
|
import pandas as pd
#Specifying excel file to create an information body
df_excel = pd.read_excel(‘test_pandas.xlsx’)
#Show column labels
print(df_excel.columns) |
Consequence:
Index([‘Product ID’, ‘Product Name’, ‘Price’, ‘Status’], dtype=’object’)
The instance of making an information body and utilizing columns property
Within the Python program beneath, we’ve created a Pandas Information body with three columns and likewise created three rows of information.
That is adopted by displaying the info body.
Lastly, we used the columns property of the DF to show column labels of the info body.
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
import pandas as pd
inflation_data = {
“12 months”: [2015, 2016, 2016, 2017],
“Inflation”: [‘3.25%’, ‘2.15%’, ‘3%’, ‘1.5%’]
}
#Making a Information body
df = pd.DataFrame(inflation_data)
#Show column labels
print(df.columns) |
Output:
Index([‘Year’, ‘Inflation’], dtype=’object’)