print the number of columns in a dataframe in python

To print the number of columns in a dataframe in Python, you can use the shape attribute of the Pandas DataFrame object. The shape attribute returns a tuple with two elements: the number of rows and the number of columns. To print just the number of columns, you can access the second element of the tuple using indexing. Here's an example:

main.py
import pandas as pd

# create a sample dataframe
data = {'col1': [1, 2, 3], 'col2': [4, 5, 6], 'col3': [7, 8, 9]}
df = pd.DataFrame(data)

# get the number of columns
num_cols = df.shape[1]

# print the number of columns
print("Number of columns:", num_cols)
259 chars
12 lines

This will output:

main.py
Number of columns: 3
21 chars
2 lines

gistlibby LogSnag