簡體   English   中英

熊貓:使用數據透視表進行數據框轉換

[英]Pandas: dataframe transformation using pivot

我有以下格式的數據框:

Date        Id       A         B         C          D        E
2018-01-28 5937.0 11.000000 11.000000 10.000000 10.000000 10.000000

2018-01-21 5937.0 10.000000 10.000000 10.000000 10.000000 10.000000

我想將數據更改為以下格式:

             Id       2018-01-28         2018-01-21
A           5937.0   11.000000          10.000000
B           5937.0   11.000000          10.000000
C           5937.0   10.000000          10.000000
D           5937.0   10.000000          10.000000
E           5937.0   10.000000          10.000000

進行以下轉換的最佳方法是什么? 我一直在使用數據透視,但無法正常工作(我對數據透視不太滿意)

使用set_index其次stackunstackreset_index

df1 = df.set_index(['Date','Id']).stack().unstack(0).reset_index(0)

print(df1)
Date      Id  2018-01-21  2018-01-28
A     5937.0        10.0        11.0
B     5937.0        10.0        11.0
C     5937.0        10.0        10.0
D     5937.0        10.0        10.0
E     5937.0        10.0        10.0

df1=df.set_index(['Date','Id']).stack().unstack(0).reset_index(0).rename_axis(None,1)

print(df1)
       Id  2018-01-21  2018-01-28
A  5937.0        10.0        11.0
B  5937.0        10.0        11.0
C  5937.0        10.0        10.0
D  5937.0        10.0        10.0
E  5937.0        10.0        10.0

我會使用meltpivot_table來做到這pivot_table

(df.melt(['Date', 'Id'])
   .pivot_table(index=['variable', 'Id'], columns='Date', values='value')
   .reset_index())


Date variable      Id  2018-01-21  2018-01-28
0           A  5937.0        10.0        11.0
1           B  5937.0        10.0        11.0
2           C  5937.0        10.0        10.0
3           D  5937.0        10.0        10.0
4           E  5937.0        10.0        10.0

使用樞軸:

(df.pivot_table(values=["A", "B", "C", "D", "E"], columns=["Id", "Date"])
    .unstack()
    .reset_index(1) # Multi-index level 1 = Id
    .rename_axis(None, 1)) # Set columns name to None (not Date)

輸出:

Date      Id  2018-01-21  2018-01-28
A     5937.0        10.0        11.0
B     5937.0        10.0        11.0
C     5937.0        10.0        10.0
D     5937.0        10.0        10.0
E     5937.0        10.0        10.0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM