Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the row count of a Pandas DataFrame?

I'm trying to get the number of rows of dataframe df with Pandas, and here is my code.

Method 1:

total_rows = df.count print total_rows + 1 

Method 2:

total_rows = df['First_column_label'].count print total_rows + 1 

Both the code snippets give me this error:

TypeError: unsupported operand type(s) for +: 'instancemethod' and 'int'

What am I doing wrong?

like image 505
yemu Avatar asked Apr 11 '13 08:04

yemu


People also ask

How do I count rows in pandas DataFrame?

Get Number of Rows in DataFrame You can use len(df. index) to find the number of rows in pandas DataFrame, df. index returns RangeIndex(start=0, stop=8, step=1) and use it on len() to get the count.

How do I count rows and columns in pandas?

To get the number of rows, and columns we can use len(df. axes[]) function in Python.

How do I count rows in pandas based on conditions?

Using count() method in Python Pandas we can count the rows and columns. Count method requires axis information, axis=1 for column and axis=0 for row. To count the rows in Python Pandas type df. count(axis=1) , where df is the dataframe and axis=1 refers to column.

How do you check Rowcount in Python?

So, for getting row counts of a DataFrame, simply use len(df) .


2 Answers

For a dataframe df, one can use any of the following:

  • len(df.index)
  • df.shape[0]
  • df[df.columns[0]].count() (== number of non-NaN values in first column)

Performance plot


Code to reproduce the plot:

import numpy as np import pandas as pd import perfplot  perfplot.save(     "out.png",     setup=lambda n: pd.DataFrame(np.arange(n * 3).reshape(n, 3)),     n_range=[2**k for k in range(25)],     kernels=[         lambda df: len(df.index),         lambda df: df.shape[0],         lambda df: df[df.columns[0]].count(),     ],     labels=["len(df.index)", "df.shape[0]", "df[df.columns[0]].count()"],     xlabel="Number of rows", ) 
like image 152
root Avatar answered Oct 01 '22 00:10

root


Suppose df is your dataframe then:

count_row = df.shape[0]  # Gives number of rows count_col = df.shape[1]  # Gives number of columns 

Or, more succinctly,

r, c = df.shape 
like image 34
Nasir Shah Avatar answered Oct 01 '22 00:10

Nasir Shah