如何迭代从groupby().size()生成的Pandas Series [英] How to iterate over Pandas Series generated from groupby().size()

查看:97
本文介绍了如何迭代从groupby().size()生成的Pandas Series的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何遍历通过.groupby('...').size()命令生成的Pandas系列并获取组名和计数.

How do you iterate over a Pandas Series generated from a .groupby('...').size() command and get both the group name and count.

例如,如果我有:

foo
-1     7
 0    85
 1    14
 2     5

我该如何遍历它们,以便每次迭代都具有-1& 7,0& 85,1& 14和2& 5个变量?

how can I loop over them so the that each iteration I would have -1 & 7, 0 & 85, 1 & 14 and 2 & 5 in variables?

我尝试了枚举选项,但效果不佳.示例:

I tried the enumerate option but it doesn't quite work. Example:

for i, row in enumerate(df.groupby(['foo']).size()):
    print(i, row)

对于i,它不会返回-1、0、1和2,而是返回0、1、2、3.

it doesn't return -1, 0, 1, and 2 for i but rather 0, 1, 2, 3.

推荐答案

更新:

给出一个熊猫系列:

s = pd.Series([1,2,3,4], index=['a', 'b', 'c', 'd'])

s
#a    1
#b    2
#c    3
#d    4
#dtype: int64

您可以直接遍历它,它在每次迭代中从序列中产生一个值:

You can directly loop through it, which yield one value from the series in each iteration:

for i in s:
    print(i)
1
2
3
4

如果要同时访问索引,可以使用itemsiteritems方法,这将生成一个同时包含索引和值的生成器:

If you want to access the index at the same time, you can use either items or iteritems method, which produces a generator that contains both the index and value:

for i, v in s.items():
    print('index: ', i, 'value: ', v)
#index:  a value:  1
#index:  b value:  2
#index:  c value:  3
#index:  d value:  4

for i, v in s.iteritems():
    print('index: ', i, 'value: ', v)
#index:  a value:  1
#index:  b value:  2
#index:  c value:  3
#index:  d value:  4


旧答案:

您可以在Series上调用iteritems()方法:

You can call iteritems() method on the Series:

for i, row in df.groupby('a').size().iteritems():
    print(i, row)

# 12 4
# 14 2

根据文档:

Series.iteritems()

Series.iteritems()

懒惰地遍历(索引,值)元组

Lazily iterate over (index, value) tuples

注意:这与问题中的数据不同,只是一个演示.

Note: This is not the same data as in the question, just a demo.

这篇关于如何迭代从groupby().size()生成的Pandas Series的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆