如何获取 Pandas 中的行数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29117012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the count of the rows in Pandas?
提问by アレックス
I want to get a count of the rows in dataframe:
我想获取数据框中的行数:
count1 = df[(df['col1'] == xxx) & (df['col2'] == yyy)].count()
But it still return Series. How can I get the actual count as int?
但它仍然返回系列。我怎样才能得到实际计数为int?
回答by アレックス
I don't know why count()doesn't work as intended, but this does work:
我不知道为什么count()不能按预期工作,但这确实有效:
df2 = df[(df['col1'] == xxx) & (df['col2'] == yyy)]
count = len(df2) # int
回答by Jose Pablo
Converting the resulting Series into a list could help you "tolist()"
将结果系列转换为列表可以帮助您“tolist()”
回答by EdChum
Unclear what you're expecting here df.count()returns a series or df showing you the row or column count, why would you expect a simple scalar value returned?
不清楚您在这里期待什么df.count()返回一个系列或 df 向您显示行数或列数,为什么您会期望返回一个简单的标量值?
If you wanted just the row cound then perform len(count)or count.shape[0]
如果您只想要行数,则执行len(count)或count.shape[0]
example:
例子:
In [173]:
df = pd.DataFrame({'a':[0,2,2,3,5], 'b':[0,1,1,3,5], 'c':np.random.randn(5)})
df
Out[173]:
a b c
0 0 0 -1.192011
1 2 1 0.290372
2 2 1 -0.092076
3 3 3 0.821918
4 5 5 0.551033
In [180]:
count1 = df[(df['a'] == 2) & (df['b']==1)]
len(count1)
Out[180]:
2

