Search code examples
pythonpandasdataframeaverage

How to combine different rows and get mean value for columns in a dataframe


I have the following df which contains 2 types of information. The first one is the characteristics of the item (some are strings and others are integers). The other type is regarding emission values of the said item (in a float format).

Charact. 1 Charact. 2 Charact. 3 Emission 1 Emission 2
1998 AB C 1 2
1998 AB C 3 4
2000 AB C 1 2
2001 DE F 1 2
2001 DE F 3 4

I would like to combine the items which have the same 3 characteristics and get the mean value of the 2 emissions to get the following df :

Charact. 1 Charact. 2 Charact. 3 Emission 1 Emission 2
1998 AB C 2 3
2000 AB C 1 2
2001 DE F 2 3

I have tried this line of code to get it to work but it gives me an error

df.groupby(['Charact. 1', 'Charact. 2', 'Charact. 3'], as_index=False).agg({'Emission 1': 'mean', 'Emission 2': 'mean',})

The specific error says : ValueError: Length of values (10345) does not match length of index (10687600)


Solution

  • df.groupby(['Charact. 1','Charact. 2', 'Charact. 3'])[['Emission 1','Emission 2']].mean()
    
                                           Emission 1   Emission 2
    Charact. 1  Charact. 2  Charact. 3      
    1998             AB              C           2.0    3.0
    2000             AB              C           1.0    2.0
    2001             DE              F           2.0    3.0