【问题标题】:How to melt the pd.DataFrame to organize the data? (toy example included)如何融化 pd.DataFrame 来组织数据? (包括玩具示例)
【发布时间】:2021-02-13 23:52:23
【问题描述】:

问题

  • 我很想知道如何将下面提供的玩具示例中的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 会有所帮助,但它不会按照我的意愿创建索引和列。

【问题讨论】:

    标签: python pandas dataframe pivot melt


    【解决方案1】:

    试试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 对Sort a pandas's dataframe series by month name? 的回答使用pd.Categorical

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-08
      • 2014-06-05
      • 1970-01-01
      • 1970-01-01
      • 2020-11-28
      相关资源
      最近更新 更多