Arthur Camberlein >> SEO & Data articles >> Know and display all column from a dataframe in Python

Know and display all column from a dataframe in Python

Written by Arthur Camberlein | Published on & updated on

How to know (and display) all columns of a dataframe in Python

Prerequisites

We will once again use the (famous) pandas library used in Python.

For installation, you have the solutions below:

for Python

pip install pandas

for Python 3

pip3 install pandas

You will only need to install your library once -- Unless you are on different environments/machines

And then you will need to load the library – each time/each script launch – and to do this:

import pandas as pd

Display columns using pandas in Python

To display the columns of a dataframe in Python, you have two solutions:

Solution 1

for col in df.columns:
  print(col)

Solution 2

print(df.columns)

For each column (col) of the dataframe df (in df.columns) and then display (print) the result using print()

Back to blog

Learn more with the article FAQ

Know and display all column from a dataframe in Python - FAQs

How can I check if a specific column exists in my DataFrame?

You can easily check if a column exists in your DataFrame using Python's 'in' operator. Here's how you can do it:

if 'column_name' in df.columns: print("Column exists in the DataFrame")else: print("Column does not exist in the DataFrame")

How do I rename columns in my DataFrame?

There are multiple ways to rename columns in a pandas DataFrame. The most straightforward method is using the rename() function. You can pass a dictionary mapping old column names to new ones:

df = df.rename(columns={'old_name': 'new_name'})

How can I get the data types of all columns in my DataFrame?

Understanding the data types of your columns is crucial for data analysis. You can easily check the data types of all columns using the dtypes attribute:

print(df.dtypes)

This will display each column name along with its corresponding data type, which is particularly useful when working with large datasets.

Blog post taggued in: Data, Python

Written by