简体   繁体   中英

How do you revert pandas pivot table back to original shape?

I took this dataframe

    name            amf L1  L2  L3
0   CpG_Island_1    0.0 a   1   x
1   CpG_Island_2    NaN a   1   x
2   CpG_Island_3    NaN a   1   x
3   CpG_Island_4    NaN a   1   x
4   CpG_Island_5    NaN a   1   x

and created a pivot table with 3-level index:

pd.pivot_table(df, values='amf',index='name',columns=['L1','L2','L3'])

L1                  a
L2                  1
L3                  x           y           z
name            
CpG_Island_1        0.000000    0.000000    0.000000
CpG_Island_10       1.000000    NaN         0.866667
CpG_Island_100      0.973684    0.938776    1.000000
CpG_Island_1000     0.555556    0.369427    0.444444
CpG_Island_10000    0.953488    0.941176    1.000000

This is the shape I need it for df.dropna() . But after dropping NaN s how do I revert it back to the original shape?

Check unstack

out = df.set_index(['L1','L2','L3','name']).unstack([0,1,2])
Out[43]: 
              amf
L1              a
L2              1
L3              x
name             
CpG_Island_1  0.0
CpG_Island_2  NaN
CpG_Island_3  NaN
CpG_Island_4  NaN
CpG_Island_5  NaN

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