如何在for循环中检索Pandas GroupBy对象的行

问题描述 投票:0回答:1

我有一个按对象分组。我想在for循环中按对象检索组的特定列的行并进行一些处理。例如,我在这里给出一个逐个对象的示例代码

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'])

分组后,我得到了以下对象

enter image description here

在for循环中,我想做一些检查,如果它是一个,两个或三个然后做一些处理。你能告诉我步骤吗?

python pandas dataframe
1个回答
2
投票

你可以像这样循环group_by对象:

for index, row in grouped:
    print (index) #index is a tuple 
    print(row) #row is a new dataframe 

要检查您要查找的内容,可以执行此操作(即:检查数据框的某个列中是否有值执行此操作):

for index, row in grouped:
    if -0.83026 in row.get("C").values: # "C" or any column name you want
        print("hello")

对于您的数据,输出将是这样的:

('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
© www.soinside.com 2019 - 2024. All rights reserved.