如何获取panda数据帧df的行数?


当前回答

这两种方法都可以做到(df是DataFrame的名称):

方法1:使用len函数:

len(df)将给出名为df的DataFrame中的行数。

方法2:使用计数函数:

df[col].count()将计算给定列col中的行数。

df.count()将给出所有列的行数。

其他回答

这两种方法都可以做到(df是DataFrame的名称):

方法1:使用len函数:

len(df)将给出名为df的DataFrame中的行数。

方法2:使用计数函数:

df[col].count()将计算给定列col中的行数。

df.count()将给出所有列的行数。

假设df是您的数据帧,那么:

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

或者更简洁地说,

r, c = df.shape

我从R背景来到Pandas,我发现Pandas在选择行或列时更加复杂。

我不得不与它搏斗一段时间,然后我找到了一些应对方法:

获取列数:

len(df.columns)
## Here:
# df is your data.frame
# df.columns returns a string. It contains column's titles of the df.
# Then, "len()" gets the length of it.

获取行数:

len(df.index) # It's similar.

假设数据集是“data”,将数据集命名为“data_fr”,data_fr中的行数为“nu_rows”

#import the data frame. Extention could be different as csv,xlsx or etc.
data_fr = pd.read_csv('data.csv')

#print the number of rows
nu_rows = data_fr.shape[0]
print(nu_rows)

对于dataframe df,在浏览数据时使用的打印逗号格式的行计数:

def nrow(df):
    print("{:,}".format(df.shape[0]))

例子:

nrow(my_df)
12,456,789