Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
524 views
in Technique[技术] by (71.8m points)

python - 如何获取大熊猫DataFrame的行数?(How do I get the row count of a pandas DataFrame?)

I'm trying to get the number of rows of dataframe df with Pandas, and here is my code.

(我正在尝试使用Pandas获取数据框df的行数,这是我的代码。)

Method 1: (方法1:)

total_rows = df.count
print total_rows +1

Method 2: (方法2:)

total_rows = df['First_columnn_label'].count
print total_rows +1

Both the code snippets give me this error:

(这两个代码段都给我这个错误:)

TypeError: unsupported operand type(s) for +: 'instancemethod' and 'int'

(TypeError:+不支持的操作数类型:“ instancemethod”和“ int”)

What am I doing wrong?

(我究竟做错了什么?)

  ask by yemu translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the .shape property or just len(DataFrame.index) .

(您可以使用.shape属性,也可以仅使用len(DataFrame.index) 。)

However, there are notable performance differences ( len(DataFrame.index) is fastest):

(但是,存在明显的性能差异( 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)

在此处输入图片说明

EDIT: As @Dan Allen noted in the comments len(df.index) and df[0].count() are not interchangeable as count excludes NaN s,

(编辑:正如@Dan Allen在评论中指出len(df.index)df[0].count()不可互换,因为count排除了NaN ,)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...