Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
418 views
in Technique[技术] by (71.8m points)

python - append rows to a Pandas groupby object

I am trying to figure out the best way to insert the means back into a multi-indexed pandas dataframe.

Suppose I have a dataframe like this:

      metric 1     metric 2    
             R   P        R   P
foo a        0   1        2   3
    b        4   5        6   7
bar a        8   9       10  11
    b       12  13       14  15

I would like to get the following result:

      metric 1     metric 2    
             R   P        R   P
foo a        0   1        2   3
    b        4   5        6   7
  AVG        2   3        4   5
bar a        8   9       10  11
    b       12  13       14  15
  AVG       10  11       12  13

Please note, I know I can do df.mean(level=0) to get the level 0 group means as a separate dataframe. This is not exactly what I want -- I want to insert the group means as rows back into the group.

I am able to get the result I want, but I feel like I am doing this wrong/there is probably a one liner that I am missing that already does this without the expensive python iteration. Here is my example code:

import numpy as np
import pandas as pd

data = np.arange(16).reshape(4,4)
row_index = [("foo", "a"), ("foo", "b"), ("bar", "a"), ("bar", "b")]
col_index = [("metric 1", "R"), ("metric 1", "P"), ("metric 2", "R"),  
    ("metric 2", "P")]
col_multiindex = pd.MultiIndex.from_tuples(col_index)
df = pd.DataFrame(data, index=pd.MultiIndex.from_tuples(row_index),
    columns=col_multiindex)

new_row_index = []
data = []
for name, group in df.groupby(level=0):
    for index_tuple, row in group.iterrows():
        new_row_index.append(index_tuple)
        data.append(row.tolist())
    new_row_index.append((name, "AVG"))
    data.append(group.mean().tolist())

print pd.DataFrame(data, 
    index=pd.MultiIndex.from_tuples(new_row_index), 
    columns=col_multiindex)

Which results in:

        metric 1     metric 2    
               R   P        R   P
bar a          8   9       10  11
    b         12  13       14  15
    AVG       10  11       12  13
foo a          0   1        2   3
    b          4   5        6   7
    AVG        2   3        4   5

which flips the order of the groups for some reason, but is more or less what I want.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The main thing you need to do here is append your means to the main dataset. The main trick you need before doing that is just to conform the indexes (with the reset_index() and set_index() so that after you append them they will be more or less lined up and ready to sort based on the same keys.

In [35]: df2 = df.groupby(level=0).mean()

In [36]: df2['index2'] = 'AVG'

In [37]: df2 = df2.reset_index().set_index(['index','index2']).append(df).sort()

In [38]: df2
Out[38]: 
             metric 1     metric 2    
                    R   P        R   P
index index2                          
bar   AVG          10  11       12  13
      a             8   9       10  11
      b            12  13       14  15
foo   AVG           2   3        4   5
      a             0   1        2   3
      b             4   5        6   7

As far as ordering the rows, the best thing is probably just to set the names so that sorting puts them in the right place (e.g. A,B,avg). Or for a small number of rows you could just use fancy indexing:

In [39]: df2.ix[[4,5,3,1,2,0]]
Out[39]: 
             metric 1     metric 2    
                    R   P        R   P
index index2                          
foo   a             0   1        2   3
      b             4   5        6   7
      AVG           2   3        4   5
bar   a             8   9       10  11
      b            12  13       14  15
      AVG          10  11       12  13

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...