How to Get the Number of Rows and Columns in a Pandas DataFrame Object in Python 


               


How to Get the Number of Rows and Columns in a Pandas DataFrame Object in Python



Python


In this article, we show how to get the number of rows and columns in a pandas dataframe object in Python.

So let's say you imported data from a Microsoft Excel spreadsheet such as CSV file or even from just a plain text file.

At times, you definitely may want to know how many rows and columns there are from this data that you are reading.

You may have a program that automatically reads a CSV file and now outputs how many rows and columns that have been read.

So how can we find out and get the number of rows and columns there are in a pandas dataframe object?

We can do this using the shape attribute.

The shape attribute displays how many rows and columns there are in a pandas dataframe object.

The shape attribute returns the number of rows and columns as a tuple.

The tuple is compose of 2 values, the rows as the first value and the columns as the second value.

This is shown in the following code below.



So let's now go over the code.

So we first have to import the pandas module. We do this with the line, import pandas as pd.

as pd means that we can reference the pandas module with pd instead of writing out the full pandas each time.

We import rand from numpy.random, so that we can populate the DataFrame with random values. In other words, we won't need to manually create the values in the table. The randn function will populate it with random values.

We create a variable, dataframe1, which we set equal to, pd.DataFrame(randn(4,3),['A','B','C','D',],['X','Y','Z'])

This creates a DataFrame object with 4 rows and 3 columns.

The rows are 'A', 'B', 'C', and 'D'.

The columns are 'W', 'X', and 'Y'.

After we output the dataframe1 object, we get the DataFrame object with all the rows and columns, which you can see above.

We then get the number of rows and columns in the dataframe object using the shape attribute.

Since there are 4 rows and 3 columns, the tuple of (4,3) is returned.

Next, to just show you that this changes if the dataframe changes, we add another column to the dataframe.

This makes the dataframe have 4 columns and 4 rows.

Now when we have the statement, dataframe1.shape, the tuple of (4,4) is returned.

So this is show we can get the number of rows and columns in a pandas dataframe object in Python.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...