Search code examples
python-3.xpandas

How to use groupby pandas dataframe with iterrows


I need to make calculations over the rows of a pandas dataframe, but I need to ake these calculations by group, so I used groupBy but when I used iterrows, I got this issue

AttributeError: 'DataFrameGroupBy' object has no attribute 'iterrows'

Please anyone can help me?

Thank


Solution

  • if I understand your problem correctly here is the answer. iterrows came from a pandas dataframe object. when you call groupby on a dataframe, you have DataFrameGroupBy object.

    so you need to iterate over DataFrameGroupBy then call iterrow for each group of it.

    d = {'a':[1,2,3,4,5],'b':[1,1,1,0,0]}
    d = pd.DataFrame(d)
    d_agg = d.groupby('b')
    for name,group in d_agg:
        print('group: ',name)
        for row,data in group.iterrows():
            print(row,data)
    

    if you have further question let me know.