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


当前回答

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

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

解决方案:

lengh = df.shape[0]

其他回答

除了前面的答案之外,您还可以使用df.axes获取具有行和列索引的元组,然后使用len()函数:

total_rows = len(df.axes[0])
total_cols = len(df.axes[1])

使用len(df):-)。

__len__()记录了“返回索引长度”。

计时信息,设置方式与root的答案相同:

In [7]: timeit len(df.index)
1000000 loops, best of 3: 248 ns per loop

In [8]: timeit len(df)
1000000 loops, best of 3: 573 ns per loop

由于有一个额外的函数调用,当然可以说它比直接调用len(df.index)慢一点。但在大多数情况下,这并不重要。我发现len(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)

我从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.

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

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

例子:

nrow(my_df)
12,456,789