首页 > 解决方案 > 有没有办法用熊猫轻松地将值与行结合起来?

问题描述

我在 Python 中使用 pandas 的 Dataframe 如下所示:

Country | Year | January | February | ...| December
Angola | 2016 | 1 | 2 | ... | 3
Angola | 2017 | 4 | 5 | ... | 6
Angola | 2018 | 7 | 8 | ... | 9
Burundi | 2016 | 10 | 11 | ... | 12

我希望它修改为:

Country | Date | value
Angola | 01.2016 | 1
Angola | 02.2016 | 2
...
Angola | 12.2016 | 3
Angola | 01.2017 | 4
Angola | 02.2017 | 5
...
Angola | 12.2017 | 6
Angola | 01.2018 | 7
Angola | 02.2018 | 8
...
Angola | 12.2018 | 9
Burundi | 01.2016 | 10
Burundi | 02.2016 | 11
...
Burundi | 12.2016 | 12

我想知道熊猫是否有这个功能?

标签: pythonpandasdataframe

解决方案


用于DataFrame.meltunpivot with 转换组合Year提取 by DataFrame.popwith to_datetime,然后按两列排序 byDataFrame.sort_values和 last 对于 datetimes 的自定义字符串使用Series.dt.strftime

df = df.melt(id_vars=['Country','Year'], var_name='Date')
df['Date'] = pd.to_datetime(df.pop('Year').astype(str) + df['Date'], format='%Y%B')
df = df.sort_values(['Country','Date'], ignore_index=True)
df['Date'] = df['Date'].dt.strftime('%m.%Y')
print (df)
    Country     Date  value
0    Angola  01.2016      1
1    Angola  02.2016      2
2    Angola  12.2016      3
3    Angola  01.2017      4
4    Angola  02.2017      5
5    Angola  12.2017      6
6    Angola  01.2018      7
7    Angola  02.2018      8
8    Angola  12.2018      9
9   Burundi  01.2016     10
10  Burundi  02.2016     11
11  Burundi  12.2016     12

DataFrame.set_index或使用and的替代解决方案DataFrame.stack,然后不需要排序:

df1 = (df.rename_axis('Date', axis=1)
         .set_index(['Country','Year'])
         .stack()
         .reset_index(name='value'))
df1['Date'] = (pd.to_datetime(df1.pop('Year').astype(str) + df1['Date'], format='%Y%B')
                 .dt.strftime('%m.%Y'))
print (df1)
    Country     Date  value
0    Angola  01.2016      1
1    Angola  02.2016      2
2    Angola  12.2016      3
3    Angola  01.2017      4
4    Angola  02.2017      5
5    Angola  12.2017      6
6    Angola  01.2018      7
7    Angola  02.2018      8
8    Angola  12.2018      9
9   Burundi  01.2016     10
10  Burundi  02.2016     11
11  Burundi  12.2016     12

推荐阅读