• Post author:
  • Post category:Pandas
  • Post last modified:March 27, 2024
  • Reading time:8 mins read
You are currently viewing Pandas Retrieve Number of Columns

Use axes(), len(), shape() and info() method to retrieve the number of columns from pandas DataFrame. In this article, I will explain how to retrieve the number of columns from pandas DataFrame with examples.

Related: Get All Header Columns from pandas DataFrame

1. Quick Examples of Retrieve Number Columns from DataFrame

If you are in a hurry, below are some quick examples of how to retrieve number columns from DataFrame.


# Below are the quick examples

# Using df.axes() method to get number columns
cols = len(df.axes[1])
count = str(cols)

# Using DataFrame.len() method 
count = len(df.columns)

# Get the number of columns and rows
shape = df.shape

# Using DataFrame.shape method
count = df.shape[1]

# Using DataFrame.info() method 
df.info()

Now, let’s create a DataFrame with a few rows and columns, execute these examples and validate the results. Our DataFrame contains column names Courses, Fee, Duration, and Discount.


# Create DataFrame
import pandas as pd
technologies = {
    'Courses':["Spark","PySpark","Python","pandas","Hadoop"],
    'Fee' :[20000,25000,22000,24000,30000],
    'Duration':['30days','40days','35days','60days','50days'],
    'Discount':[1000,2300,2500,2000,3000]
              }
index_labels=['r1','r2','r3','r4','r5']
df = pd.DataFrame(technologies,index=index_labels)
print(df)

Yields below output.


# Output:
    Courses    Fee Duration  Discount
r1    Spark  20000   30days      1000
r2  PySpark  25000   40days      2300
r3   Python  22000   35days      2500
r4   pandas  24000   60days      2000
r5   Hadoop  30000   50days      3000

2. Retrieve Number Columns using DataFrame.axes()

Use DataFrame.axes() method in pandas to retrieve the number of columns. It accepts the argument ‘1’ for columns and ‘0’ for rows. For instance, len(df.axes[1]) returns the number of columns from the DataFrame.


# Using df.axes() method to get number of columns
cols = len(df.axes[1])
count = str(cols)
print("Get number of Columns: " + count)

Yields below output.


# Output:
Get number of Columns: 4

3. Using DataFrame.len() Method to Retrieve Number Columns

You can also use DataFrame.len() method to retrieve the number of columns, To use this you need to pass the columns list as an argument. For example, len(df.columns) gets you the number of columns. Here, the df.columns return the DataFrame column names as a list.


# Using DataFrame.len() method 
count = len(df.columns)
print("Get number of Columns:", count)

Yields the same output as above.

4. Using DataFrame.shape() Method

pandas DataFrame also provides shape property that returns the shape of DataFrame as a tuple that includes the number of columns and rows, where the shape[0] gives a number of rows and shape[1] gives the number of columns.


# Get the number of columns and rows
df.shape

# Using DataFrame.shape[1] to get columns count
columns_count = df.shape[1]
print("Get number of Columns:", columns_count)

Yields the same output as above.

5. Using DataFrame.info() Method

DataFrame.info() method provides information about the DataFrame including dtype of columns, row indexes, memory usage, number of columns, etc.


# Using DataFrame.info() method 
df.info()

Yields below output.


# Output:
<class 'pandas.core.frame.DataFrame'>
Index: 5 entries, r1 to r5
Data columns (total 4 columns):
 #   Column    Non-Null Count  Dtype 
---  ------    --------------  ----- 
 0   Courses   5 non-null      object
 1   Fee       5 non-null      int64 
 2   Duration  5 non-null      object
 3   Discount  5 non-null      int64 
dtypes: int64(2), object(2)
memory usage: 200.0+ bytes

6. Complete Example For Retrieve Number Columns From DataFrame


import pandas as pd
technologies = {
    'Courses':["Spark","PySpark","Python","pandas","Hadoop"],
    'Fee' :[20000,25000,22000,24000,30000],
    'Duration':['30days','40days','35days','60days','50days'],
    'Discount':[1000,2300,2500,2000,3000]
              }
index_labels=['r1','r2','r3','r4','r5']
df = pd.DataFrame(technologies,index=index_labels)
print(df)

# Using df.axes() method to get number columns
cols = len(df.axes[1])
count = str(cols)
print("Get number of Columns: " + count)

# Using DataFrame.len() method 
count = len(df.columns)
print("Get number of Columns:", count)

# Using DataFrame.shape method
count = df.shape[1]
print("Get number of Columns:", count)

# Get the number of columns and rows
shape = df.shape
print(shape)

# Using DataFrame.info() method 
df.info()

7. Conclusion

In this article, you have learned how to retrieve the number of columns from DataFrame using axes(), len(), shape() and info() method with examples. When you use the shape, use the shape[1] to retrieve the number of columns.

Happy Learning !!

References

Malli

Malli is an experienced technical writer with a passion for translating complex Python concepts into clear, concise, and user-friendly articles. Over the years, he has written hundreds of articles in Pandas, NumPy, Python, and takes pride in ability to bridge the gap between technical experts and end-users.

Leave a Reply