简体   繁体   中英

How to make a pivot table from this data?

I have data like

data = {
    "Person": ["A", "A", "A", "B", "B", "B"],
    "Month": [1, 2, 3, 1, 2, 3],
    "Value 1": [5, 6, 7, 8, 9, 10],
    "Value 2": [10, 11, 12, 13, 5, 4]

}

df = pd.DataFrame(data)

I want it to look like:

  Person   Value    Month 1  Month 2  Month 3  
0      A   1        5        6       7         
0      A   2        10       11      12        
0      B   1        8        9       10       
0      B   2        13       5       4        
...

How would I go about doing this?

IIUC, can pivot_table + unstack

df.pivot_table(columns='Month', index='Person')\
  .unstack()\
  .reset_index()\
  .rename(columns={'level_0': 'Value'})\
  .pivot_table(columns='Month', index=['Person', 'Value'])

Outputs

        Month          1       2        3       5       6
Person  Value                   
A       Value   1      5.0      6.0     7.0     NaN     NaN
        Value   2      10.0     11.0    12.0    NaN     NaN
B       Value   1      NaN      NaN     NaN     8.5     10.0
        Value   2      NaN      NaN     NaN     9.0     4.0

Another option using melt

df1=df.melt(['Person','Month'])\
.pivot_table(index=['Person','variable'], columns=['Month'])
df1.index.rename(['Person','Value'], inplace=True)
df1.columns=df1.columns.droplevel()

        Month   1   2   3   5   6
Person  Value                   
A   Value 1     5.0 6.0 7.0 NaN NaN
    Value 2     10.0 11.0 12.0 NaN NaN
B   Value 1     NaN NaN NaN 8.5 10.0
    Value 2     NaN NaN NaN 9.0 4.0

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