- 问题:
-
我试着用Pandas得到数据帧df的行数,这是我的代码
total_rows = df.count
print total_rows +1total_rows = df['First_columnn_label'].count
print total_rows +1两个代码片段都给出了以下错误:
TypeError:不支持+:“instancemethod”和“int”的操作数类型
我做错什么了?在
- 答案:
-
您可以使用
.shape
属性或仅使用len(数据帧.索引)
。但是,有显著的性能差异(len(数据帧.索引)
最快):In [1]: import numpy as np
In [2]: import pandas as pd
In [3]: df = pd.DataFrame(np.arange(12).reshape(4,3))
In [4]: df
Out[4]:
0 1 2
0 0 1 2
1 3 4 5
2 6 7 8
3 9 10 11
In [5]: df.shape
Out[5]: (4, 3)
In [6]: timeit df.shape
2.77 µs ± 644 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [7]: timeit df[0].count()
348 µs ± 1.31 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [8]: len(df.index)
Out[8]: 4
In [9]: timeit len(df.index)
990 ns ± 4.97 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)编辑:正如@Dan Allen在评论中提到的
len(测向索引)
和df[0].count()
不可互换,因为count
排除了NaN
s