簡體   English   中英

我如何 pivot 和堆疊 Pandas DataFrame?

[英]How can I pivot AND stack a Pandas DataFrame?

作為 Pandas 的一個相當少見的用戶,我想知道如何最好地使用 pivot 一列(代表時間),使其水平流動,同時基於另一列或索引堆疊 rest。

這就是我的意思:

data = [
    [2018, "Alex", 172, 61], [2019, "Alex", 173, 62], [2020, "Alex", 173, 63],
    [2018, "Bill", 168, 59], [2019, "Bill", 168, 59], [2020, "Bill", 169, 60],
    [2018, "Cody", 193, 67], [2019, "Cody", 194, 69], [2020, "Cody", 194, 68],
]

df = pd.DataFrame(data, columns=["year", "name", "height", "weight"])

這使:

year  name  height  weight

2018  Alex  172     61
2019  Alex  173     62
2020  Alex  173     63
2018  Bill  168     59
2019  Bill  168     59
2020  Bill  169     60
2018  Cody  193     67
2019  Cody  194     69
2020  Cody  194     68

我想 pivot 這個 DataFrame 水平流動,使年份水平流動(升序),同時基本上堆疊按名稱分組的所有其他列,以便我的 dataframe 看起來像這樣:

Alex           2018  2019  2020
      height    172   173   173
      weight     61    62    63
Bill
      height    168   168   169
      weight     59    59    60
Cody
      height    193    194   69
      weight     67    194   68

總之,我想在這里完成三件事:

  1. Pivot 橫向逐年
  2. 確保年份按升序排列,即從最低到最高
  3. 按名稱列對剩余列進行分組和堆疊

網上有很多關於單獨旋轉和堆疊的資源,但通常不像我試圖做的那樣在一起。

讓我們做set_index然后stack以將heightweight轉換為行標簽,並unstack year以將year級別轉換為列:

new_df = df.set_index(['year', 'name']).stack().unstack('year')

new_df

year         2018  2019  2020
name                         
Alex height   172   173   173
     weight    61    62    63
Bill height   168   168   169
     weight    59    59    60
Cody height   193   194   194
     weight    67    69    68

*注意: stackunstack將在 reshaping 時對索引級別進行排序。

嘗試這個:

df.set_index(['year', 'name']).stack().unstack(0)
>>>
        year    2018    2019    2020
name                
Alex    height  172     173     173
        weight  61      62      63
Bill    height  168     168     169
        weight  59      59      60
Cody    height  193     194     194
        weight  67      69      68

暫無
暫無

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

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