簡體   English   中英

如何融化 pd.DataFrame 來組織數據? (包括玩具示例)

[英]How to melt the pd.DataFrame to organize the data? (toy example included)

問題

  • 我好奇地想知道如何融化data_df在下面提供的玩具例子desired_df
import pandas as pd

data_df = pd.DataFrame(data = [['FR','Aug',100], ['FR','Sep',170], ['FR','Oct',250],
                               ['KR','Aug',9], ['KR','Sep',12],['KR','Oct',19],
                               ['US','Aug',360], ['US','Sep',500], ['US','Oct',700]],
                       columns = ['country','time','covid19'])
data_df
>>>   country   time    covid19 
   0    FR       Aug      100
   1    FR       Sep      170
   2    FR       Oct      250
   3    KR       Aug       9
   4    KR       Sep      12
   5    KR       Oct      19
   6    US       Aug      360
   7    US       Sep      500
   8    US       Oct      700
  • 我想要的輸出desired_df如下, columns國家名稱、 index時間以及數據框中 Covid 19 患者的數量作為values
desired_df
>>>     FR  KR  US
 Aug    100 9   360
 Sep    170 12  500
 Oct    250 19  700
  • 我認為pd.melt會有所幫助,但它不會按照我的pd.melt創建索引和列。

嘗試pivot

data = data_df.pivot(index = 'time', columns = 'country')
print(data)

這使:

country      FR  KR   US
time                    
Aug         100   9  360
Oct         250  19  700
Sep         170  12  500

索引按字母順序排列。 根據需要重新排列它們。 為了按日歷排序它們,我建議 Brad Solomon 的回答按月份名稱對熊貓的數據框系列進行排序? ,它使用pd.Categorical

暫無
暫無

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

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