我正在尝试用Pandas获取dataframe df的行数,这是我的代码.
方法1:
total_rows = df.count
print total_rows +1
方法2:
total_rows = df['First_columnn_label'].count
print total_rows +1
TypeError: unsupported operand type(s) for +: ‘instancemethod’ and ‘int’
我究竟做错了什么?
解决方法:
您可以使用.shape属性或只使用len(DataFrame.index).但是,有显着的性能差异(len(DataFrame.index)最快):
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.index)和df [0] .count()不可互换,因为计数不包括NaNs,
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。