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


当前回答

您也可以这样做:

假设df是您的数据帧。然后df.shape为您提供数据帧的形状,即(行,列)

因此,分配以下命令以获得所需的

 row = df.shape[0], col = df.shape[1]

其他回答

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

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

或者更简洁地说,

r, c = df.shape

使用len(df)或len(df.index)时,可能会遇到以下错误:

----> 4 df['id'] = np.arange(len(df.index)
TypeError: 'int' object is not callable

解决方案:

lengh = df.shape[0]

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

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

例子:

nrow(my_df)
12,456,789

我不确定这是否可行(数据可以省略),但这可能可行:

*dataframe name*.tails(1)

然后使用这个,您可以通过运行代码片段并查看提供给您的行号来找到行数。

如果要在链接操作的中间获取行数,可以使用:

df.pipe(len)

例子:

row_count = (
      pd.DataFrame(np.random.rand(3,4))
      .reset_index()
      .pipe(len)
)

如果您不想在len()函数中放一个长语句,这可能很有用。

您可以改用__len__(),但__len__)看起来有点奇怪。