Pandas get column names

pandas python

Pandas get column names : When analyzing large datasets, it may be necessary to obtain column names to perform certain operations on the dataset. In this article, I will show you four ways to retrieve column names in a Pandas dataframe.

Let’s start by creating a relatively simple dataset.

# Import pandas package  
import pandas as pd  
    
# Import dataset from csv
df=pd.read_csv("http://samplecsvs.s3.amazonaws.com/SacramentocrimeJanuary2006.csv")  
    
# Displays the first lines 
df_head = data.head()  
df_head 
dataset example pandas

Now let’s try to get the names of the columns in the above data set.


1st method: Iterate on the names of the column :
# iterating the columns 
for col in df.columns: 
    print(col)

Result :


Pandas get column names
2nd method : Using the .columns function :
# list(df) or 
list(df.columns) 

Result :

Pandas get column names
3rd method : the column.values function returns an index array.
list(df.columns.values) 

Result :

Pandas get column names
4th method: Using the sorted() function
# using sorted() method 
sorted(df) 

Result :

Pandas get column names
5th method: Using a tolist() function
list(df.columns.values.tolist()) 

Result :

sorted function

If you need help to install the pandas module, I advise you to have a look at this link : https://amiradata.com/pip-install-specific-version/

I advise you to have a look at the Official documentation which is rather well provided 🙂

By ayed_amira

I'm a data scientist. Passionate about new technologies and programming I created this website mainly for people who want to learn more about data science and programming :)

1 comment

Leave a comment

Your email address will not be published.