how to get number of columns in a dataframe in python

To get the number of columns in a pandas dataframe you can use the shape attribute and select the number of columns by accessing the second value of the resulting tuple. Here's an example:

main.py
import pandas as pd

# create a dataframe
df = pd.DataFrame({
    'col1': [1, 2, 3],
    'col2': ['a', 'b', 'c'],
    'col3': [4.0, 5.0, 6.0]
})

# get the number of columns
num_cols = df.shape[1]
print(num_cols)  # output: 3
226 chars
13 lines

In this example, df.shape returns a tuple with two values: the number of rows and the number of columns. Since we want the number of columns, we access the second value of the tuple by indexing with [1].

related categories

gistlibby LogSnag