简体   繁体   中英

Python dataframe reformat to multi-index

How can I convert the below origin dataframe into the output dataframe please?

origin:

**Date, Name, P1, P2**    
date1, name1, 2.0, 3.0
date2, name1, 3.1, 2.3
date1, name2, 3.4, 2.4
date2, name2, 2.0, 3.0

output:

**name1, name2**
**DATE**   **P1, P2; P1; P2**
date1, 2.0, 3.0; 3.4, 2.4
date2, 3.1, 2.3; 2.0, 3.0

I thought of a trouble way to do it, which is to filter the name and concat the result dataframe blocks. But it seems quite stupid the way. any chance you guys can help please?

You can use set_index + unstack + swaplevel + sort_index :

df = df.set_index(['Date','Name']).unstack().swaplevel(0,1, axis=1).sort_index(axis=1)
print (df)
Name  name1      name2     
         P1   P2    P1   P2
Date                       
date1   2.0  3.0   3.4  2.4
date2   3.1  2.3   2.0  3.0

print (df.columns)
MultiIndex(levels=[['name1', 'name2'], ['P1', 'P2']],
           labels=[[0, 0, 1, 1], [0, 1, 0, 1]],
           names=['Name', None])

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