pandas DataFrame shape - How to count rows and columns of a DataFrame

pandas DataFrame has count method returns the number of rows in each column.

import pandas

a = [
    ('Texas', 29),
    ('New York', 19),
    ('California', 40),
    ('Florida', 21),
]

df = pandas.DataFrame(a, columns=['State', 'Population'])

print(df)
#         State  Population
# 0       Texas          29
# 1    New York          19
# 2  California          40
# 3     Florida          21

count = df.count()

print(count)
# State         4
# Population    4
# dtype: int64

shape = df.shape

print(shape)  # (4, 2)

count displays the table of column name and the number of rows but it looks hard to use. The more simple way is using shape attribute like NumPy. This returns the number of rows and columns as a tuple.

import pandas

a = [
    ('Texas', 29),
    ('New York', 19),
    ('California', 40),
    ('Florida', 21),
]

df = pandas.DataFrame(a, columns=['State', 'Population'])

print(df)
#         State  Population
# 0       Texas          29
# 1    New York          19
# 2  California          40
# 3     Florida          21

r, c = df.shape

print(r)  # 4
print(c)  # 2

Comments

Powered by Markdown

More