简体   繁体   中英

How can I get pivot_table to apply a function over combinations of values?

I have a pandas dataframe, and I want to get the averages of the values in one column for each combination of the values in two others.

That is, if I had a dataframe like this:

 Temperature   Apple      Banana
 50            MacIntosh  Gran Michel
 28            Jazz       Cavendish
 4             MacIntosh  Canvenish
 100           MacIntosh  Gran Michel

I would want a summary like this:

 MacIntosh Gran Michel 75
 Jazz      Cavendish   28
 MacIntosh Cavendish   4
>>> df.groupby(['Apple', 'Banana'], as_index=False).mean()
       Apple       Banana  Temperature
0       Jazz    Cavendish           28
1  MacIntosh    Cavendish            4
2  MacIntosh  Gran Michel           75

Or if you want a new index:

>>> df.groupby(['Apple', 'Banana']).mean()
                       Temperature
Apple     Banana                  
Jazz      Cavendish             28
MacIntosh Cavendish              4
          Gran Michel           75

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM