如何获取panda数据帧df的行数?
当前回答
假设数据集是“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
这两种方法都可以做到(df是DataFrame的名称):
方法1:使用len函数:
len(df)将给出名为df的DataFrame中的行数。
方法2:使用计数函数:
df[col].count()将计算给定列col中的行数。
df.count()将给出所有列的行数。
对于数据帧df,可以使用以下任一项:
长度(df.索引)df.形状[0]df[df.columns[0]].count()(==第一列中非NaN值的数量)
再现绘图的代码:
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",
)
找出数据帧中行数的另一种方法是pandas.Index.size,我认为这是最可读的变体。
请注意,正如我对公认答案的评论,
疑似pandas.Index.size实际上比len(df.Index)更快,但在我的计算机上告诉的是相反的情况(每个循环大约慢150 ns)。
使用len(df)或len(df.index)时,可能会遇到以下错误:
----> 4 df['id'] = np.arange(len(df.index)
TypeError: 'int' object is not callable
解决方案:
lengh = df.shape[0]