Coding Ref

How to get the number of columns in a Pandas DataFrame

How to get the number of columns in a Pandas DataFrame

To get the number of columns in a Pandas DataFrame, you can use the shape attribute, which returns a tuple containing the number of rows and columns in the DataFrame.

The second element of the tuple (index 1) represents the number of columns.

For example, consider the following DataFrame:

main.py
import pandas as pd

df = pd.DataFrame({
    'A': [1, 2, 3, 4, 5],
    'B': [10, 20, 30, 40, 50],
    'C': [100, 200, 300, 400, 500]
})

This DataFrame has three columns A, B, and C, with five rows of data.

To get the number of columns in this DataFrame, you could do the following:

main.py
import pandas as pd

df = pd.DataFrame({
    'A': [1, 2, 3, 4, 5],
    'B': [10, 20, 30, 40, 50],
    'C': [100, 200, 300, 400, 500]
})

# Get the number of columns in the DataFrame
num_columns = df.shape[1]

# Print the number of columns
print(num_columns)
output
3

In the code above, the shape attribute is used to get the number of rows and columns in the DataFrame. The second element of the tuple (index 1) is then accessed to get the number of columns. In this case, the output is 3, indicating that the DataFrame has three columns.

You can also use the len function to get the number of columns in a DataFrame. For example, the following code uses the len function to get the number of columns:

main.py
import pandas as pd

df = pd.DataFrame({
    'A': [1, 2, 3, 4, 5],
    'B': [10, 20, 30, 40, 50],
    'C': [100, 200, 300, 400, 500]
})

# Get the number of columns in the DataFrame
num_columns = len(df.columns)

# Print the number of columns
print(num_columns)

In the code above, the columns attribute is used to get a list of the columns in the DataFrame. The len function is then applied to this list to get the number of columns. In this case, the output is 3, indicating that the DataFrame has three columns.

You'll also like

Related tutorials curated for you

    How to convert a series to a list in Pandas

    What is categorical data in Pandas?

    How to change the order of columns in Pandas

    How to use Timedelta in Pandas

    How to use pandas map() function

    How to split a Pandas DataFrame by a column value

    How to use applymap() in Pandas

    How to calculate the standard deviation in Pandas DataFrame

    How to calculate covariance in Pandas

    How to make a crosstab in Pandas

    How to drop an index column in Pandas

    How to use ffill() in Pandas