How to retrieve rows of a Pandas GroupBy object in for loop

前端 未结 1 1727
一个人的身影
一个人的身影 2021-01-27 18:05

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 f

相关标签:
1条回答
  • 2021-01-27 18:40

    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
    
    0 讨论(0)
提交回复
热议问题