简体   繁体   中英

Pandas stack groupby to DataFrame MultiIndex without aggregating

Several questions posted about transforming pandas groupby object to DataFrame seem to involve aggregation, as eg count() here .

Can a groupby object be converted to a DataFrame without aggregating, where the group names become level 0 of a MultiIndex? and can this process be iterated?

from pandas import DataFrame as DF

df = DF.from_dict({'a':1, 'b':2, 'c':3, 'd':4, 'e':5}, orient='index')

would like the output of the grouping:

df.groupby(lambda x: df[0][x]%2)

converted to this form:

DF.from_dict({0:{'b':2,'d':4},1:{'a':1,'c':3,'e':5}},orient='index').stack().to_frame()

在此处输入图片说明

(besides the point, why are values converted to floats?)

Use pd.concat , it accepts a dictionary:

pd.concat({k: v for k, v in df.groupby(lambda x: df.loc[x, 0] % 2)})

     0
0 b  2
  d  4
1 a  1
  c  3
  e  5

Iterate over each group and build your dictionary. The dictionary can be constructed using a dictionary comprehension .


A slightly faster solution not involving a callable can be done with,

pd.concat({k: v for k, v in df.groupby(df.iloc[:,0] % 2)})

     0
0 b  2
  d  4
1 a  1
  c  3
  e  5

If you need, do this again and again, try a function,

def add_level(df, grouper):
    return pd.concat({k: v for k, v in df.groupby(by=grouper)})

r = add_level(df, df.iloc[:,0] % 3)
add_level(r, r.iloc[:, 0] % 2)

       0
0 1 d  4
  2 b  2
1 0 c  3
  1 a  1
  2 e  5

Using assign chain with set_index

df.assign(indexlevel=np.arange(len(df))%2).\
    set_index('indexlevel',append=True).\
      swaplevel(0,1).\
       sort_index(level=0)
Out[30]: 
              0
indexlevel     
0          a  1
           c  3
           e  5
1          b  2
           d  4

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