如何获取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]

其他回答

使用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])

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

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

或者更简洁地说,

r, c = df.shape

找出数据帧中行数的另一种方法是pandas.Index.size,我认为这是最可读的变体。

请注意,正如我对公认答案的评论,

疑似pandas.Index.size实际上比len(df.Index)更快,但在我的计算机上告诉的是相反的情况(每个循环大约慢150 ns)。

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