python - 有没有办法用熊猫轻松地将值与行结合起来?
问题描述
我在 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
我想知道熊猫是否有这个功能?
解决方案
用于DataFrame.melt
unpivot with 转换组合Year
提取 by DataFrame.pop
with 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
推荐阅读
- python - seaborn 热图显示轴标签,但当 df.corr 为 NaN 时没有值
- r - 从 R 读取 CSV 返回错误和奇怪的 html
- linux - Flutter Chrome Executable 仅适用于铬
- r - 后续行动:将 data.frame 中缺失的列放回 dta.frames 列表中
- html - scaleX 在关键帧中自动增加
- ethereum - ERC20:尝试从我自己的简单 DEX 购买我自己的 ERC20 代币(基于 OpenZeppelin)时出现零地址异常
- javascript - 无法从 React JS 中的表单中检索查询词
- javascript - 用逗号分割字符串,不留下空格
- r - 更改 ggpairs 图中的字体和文本大小
- excel - Application.Workbooks.Open >> 文件有 CustomUI >> 错误 400