如何在for循环中检索Pandas GroupBy对象的行 [英] How to retrieve rows of a Pandas GroupBy object in for loop
问题描述
我有一个按对象分组.我想在for循环&中检索按对象分组的特定列的行.做一些处理.例如,我在这里给出了按对象分组的示例代码
I have a group by object.I want to retrieve rows of a particular column of the group by object in for loop & do some processing. For example,I'm giving here a sample code for group by object
df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
'foo', 'bar', 'foo', 'foo'],
'B' : ['one', 'one', 'two', 'three',
'two', 'two', 'one', 'three'],
'C' : np.random.randn(8),
'D' : np.random.randn(8)})
grouped = df.groupby(['A', 'B'])
分组之后,我得到了追踪对象
After group by, I got following object
在for循环中,我想检查一下它是一个,两个还是三个&然后做一些处理.您能建议我一些步骤吗?
In a for loop I would like to do some check if it's one,two or three & then do some processing.Can you please suggest me the steps?
推荐答案
您可以像这样在group_by对象中循环:
you can loop in the group_by object like this :
for index, row in grouped:
print (index) #index is a tuple
print(row) #row is a new dataframe
要检查您要查找的内容,可以执行此操作(即:检查值是否在数据框的特定列中):
To check what you are looking for you can do this(ie: check if a value is in a certain column of a dataframe do this):
for index, row in grouped:
if -0.83026 in row.get("C").values: # "C" or any column name you want
print("hello")
对于您的数据,输出将如下所示:
for your data the output will be something like this :
('bar', 'one')
A B C D
1 bar one -0.83026 0.983017
('bar', 'three')
A B C D
3 bar three -0.381041 1.538971
('bar', 'two')
A B C D
5 bar two -0.963402 0.201348
('foo', 'one')
A B C D
0 foo one 0.691410 0.328420
6 foo one -1.521541 -0.188345
('foo', 'three')
A B C D
7 foo three -0.817304 -0.359331
('foo', 'two')
A B C D
2 foo two -0.528639 -0.999301
4 foo two -1.018919 0.661665
这篇关于如何在for循环中检索Pandas GroupBy对象的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!