To get the total number of elements in a pandas DataFrame, we can use the pandas DataFrame size property.
df.size # Returns number of rows times number of columns
You can also find the number of elements in a DataFrame column or Series using the pandas size property.
df["Column"].size # Returns number of rows
When working with data, it is useful for us to be able to find the number of elements in our data. When working with pandas DataFrames, we can find the total number of elements in a DataFrame with the pandas DataFrame size() property.
Let’s say we have the following DataFrame.
df = pd.DataFrame({'Age': [43,23,71,49,52,37],
'Test_Score':[90,87,92,96,84,79]})
print(df)
# Output:
Age Test_Score
0 43 90
1 23 87
2 71 92
3 49 96
4 52 84
5 37 79
To get the size of this DataFrame, we access the size property in the following Python code.
print(df.size)
# Output:
12
Getting Size of Column in pandas DataFrame
To get the size of a column in pandas, we can access the size property in the same way as above. The size of a column is the total number of rows in that column.
Let’s say we have the same DataFrame as above and want to find the number of rows in the column “Age”. We can do so easily with the following Python code:
print(df["Age"].size)
# Output:
6
Getting the Size of a Series in pandas
To get the size of a Series in pandas, we can access the size property in the same way as above. The size of a Series is the total number of rows in that column.
Let’s say we have the same DataFrame as above and want to find the number of rows in the Series created from the column “Age”. To make a series, we convert the column to a Series, and then access the size property.
print(pd.Series(df["Age"]).size)
# Output:
6
As expected, this is the same result as accessing the size property on the column “Age”.
Hopefully this article has been helpful for you to understand how to find the size of a pandas DataFrame and get the total number of elements in a DataFrame.
Leave a Reply