Python pandas column count

Pandas | Count Number of Columns in a Dataframe

This article will discuss different ways to count the number of columns in a pandas dataframe in Python.

Table of Contents:

Let’s first create a dataframe from a list of tuples i.e.

import pandas as pd # List of Tuples students = [('jack', 34, 'Sydeny', 'Australia'), ('Riti', 30, 'Delhi', 'India'), ('Vikas', 31, 'Mumbai', 'India'), ('Neelu', 32, 'Bangalore', 'India'), ('John', 16, 'New York', 'US'), ('Mike', 17, 'las vegas', 'US')] # Create a DataFrame object from list of tuples df = pd.DataFrame( students, columns=['Name', 'Age', 'City', 'Country'], index=['a', 'b', 'c', 'd', 'e', 'f']) # Print the contents of the Dataframe print(df)

Contents of the dataframe are,

Name Age City Country a jack 34 Sydeny Australia b Riti 30 Delhi India c Vikas 31 Mumbai India d Neelu 32 Bangalore India e John 16 New York US f Mike 17 las vegas US

There are 4 columns in this Dataframe. Let’s see different ways to programmatically count the number of columns in this dataframe in Python.

Читайте также:  Python mysql connector ssh

Frequently Asked:

Count the total number of columns in a Dataframe using len()

In Pandas, the dataframe has the attribute “columns”, which give an Index object containing the column Names. We can directly call the len() function with this Index object. It will provide us with the total number of columns in the dataframe. For example,

# Get total number of columns in a Dataframe num_of_columns = len(df.columns) print(num_of_columns)

As there were four columns in the dataframe, therefore we got the number 4.

Count the total number of columns in a Dataframe using shape

In Pandas, the dataframe provides an attribute shape. It returns a tuple representing the dimensions of the dataframe i.e., the number of rows and columns of the dataframe. We can fetch the value at index position one from this tuple, and it will give us the number of columns in the dataframe. For example

# Get total number of columns in a Dataframe num_of_columns = df.shape[1] print(num_of_columns)

As there were four columns in the dataframe, therefore we got the number 4.

Count the total number of columns in a Dataframe using the size attribute

In Pandas, the dataframe has the attribute ‘columns’, which give an Index object of column Names. We can use the ‘size’ attribute of this index object. It will provide the total number of columns in the dataframe. For example,

# Get total number of columns in a Dataframe num_of_columns = df.columns.size print(num_of_columns)

As there were four columns in the dataframe, therefore we got the number 4.

The complete working example is as follows,

import pandas as pd # List of Tuples students = [('jack', 34, 'Sydeny', 'Australia'), ('Riti', 30, 'Delhi', 'India'), ('Vikas', 31, 'Mumbai', 'India'), ('Neelu', 32, 'Bangalore', 'India'), ('John', 16, 'New York', 'US'), ('Mike', 17, 'las vegas', 'US')] # Create a DataFrame object from list of tuples df = pd.DataFrame( students, columns=['Name', 'Age', 'City', 'Country'], index=['a', 'b', 'c', 'd', 'e', 'f']) # Print the contents of the Dataframe print(df) print('Count Total Number of Columns in a Dataframe') # Get total number of columns in a Dataframe num_of_columns = len(df.columns) print(num_of_columns) # Get total number of columns in a Dataframe num_of_columns = df.shape[1] print(num_of_columns) # Get total number of columns in a Dataframe num_of_columns = df.columns.size print(num_of_columns)
Name Age City Country a jack 34 Sydeny Australia b Riti 30 Delhi India c Vikas 31 Mumbai India d Neelu 32 Bangalore India e John 16 New York US f Mike 17 las vegas US Count Total Number of Columns in a Dataframe 4 4 4

We learned about three different ways to count the total number of rows in the dataframe.

Share your love

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Terms of Use

Disclaimer

Copyright © 2023 thisPointer

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

How to Get Pandas Columns Count

Use shape[] , len() , list() and info() function to count columns from pandas DataFrame. In this article, I will explain how to count the number of columns from DataFrame by using these functions with examples.

1. Quick Examples of Count Columns of DataFrame

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

Now, Let’s create Pandas DataFrame using data from a Python dictionary, where the columns are Courses , Fee , Duration and Discount .

) index_labels=['r1','r2','r3','r4'] df = pd.DataFrame(technologies,index=index_labels) print(df) 

2. Use DataFrame.shape() Function to count columns

Pandas DataFrame provides a shape property that returns the number of count columns and rows shape of the DataFrame in a tuple, where the shape[0] element is a row count and shape[1] is the columns count. Below is an example. To learn more about shape, refer to DataFrame.shape[]

3. Use len() Function to Count Columns

You can also use len() function to count columns in a DataFrame. For example len(df.columns) returns the number of columns in a DataFrame.

4. Use list() to count columns

Alternatively, You can also use the list() with the combination of len() function to get the count of DataFrame columns. Here, list() takes the dataframe as input and returns the data in a list.

5. Using Pandas DataFrame.info() Function

Pandas DataFrame.info() function provides information about the DataFrame including dtype of columns, index, memory usage, count columns, etc.

6. Complete Example For Count Columns

) index_labels=['r1','r2','r3','r4'] df = pd.DataFrame(technologies,index=index_labels) print(df) # Pandas count columns using DataFrame.shape() df2 = df.shape[1] print(df2) # Pandas count columns and rows df2 = df.shape print(df2) # Pandas count columns using len() df2 = len(df.columns) print(df2) # Using columns property col = df.columns df2 = len(col) print(df2) # Pandas count columns using list() df_list = list(df) df2 = len(df_list) print(df2) # Using DataFrame.info() function df2 = df.info() print(df2) 

7. Conclusion

In this article, I have explained how to count columns in pandas DataFrame using shape[] , len() , list() , and info() functions with examples.

  • Pandas DataFrame count() Function
  • Pandas Count Unique Values in Column
  • Count NaN Values in Pandas DataFrame
  • How to Create Pandas Pivot Table Count
  • Pandas Count Distinct Values DataFrame
  • Pandas melt() DataFrame Example
  • Pandas groupby() and count() with Examples
  • Pandas Get Count of Each Row of DataFrame
  • How to Count Duplicates in Pandas DataFrame
  • Pandas Count The Frequency of a Value in Column
  • Select pandas columns based on condition

References

You may also like reading:

Источник

pandas.DataFrame.count#

The values None , NaN , NaT , and optionally numpy.inf (depending on pandas.options.mode.use_inf_as_na ) are considered NA.

Parameters axis , default 0

If 0 or ‘index’ counts are generated for each column. If 1 or ‘columns’ counts are generated for each row.

numeric_only bool, default False

Include only float , int or boolean data.

Returns Series or DataFrame

For each column/row the number of non-NA/null entries. If level is specified returns a DataFrame .

Number of non-NA elements in a Series.

Count unique combinations of columns.

Number of DataFrame rows and columns (including NA elements).

Boolean same-sized DataFrame showing places of NA elements.

Constructing DataFrame from a dictionary:

>>> df = pd.DataFrame("Person": . ["John", "Myla", "Lewis", "John", "Myla"], . "Age": [24., np.nan, 21., 33, 26], . "Single": [False, True, True, True, False]>) >>> df Person Age Single 0 John 24.0 False 1 Myla NaN True 2 Lewis 21.0 True 3 John 33.0 True 4 Myla 26.0 False 

Notice the uncounted NA values:

>>> df.count() Person 5 Age 4 Single 5 dtype: int64 

Counts for each row:

>>> df.count(axis='columns') 0 3 1 2 2 3 3 3 4 3 dtype: int64 

Источник

Оцените статью