Pandas dataframe 使用列作为行(融化)
Pandas dataframe use columns as rows (melt)
我知道,这个问题已经被问过好几次了,但我没能根据已经问过的问题来构建我的解决方案。
DF 我有:
id| country | series name | 2015 | 2016 | 2017
--+----------+----------------+------+------+------
0 | saudi | fertility rate | 1 | 2 | 2 |
1 | saudi | CO2 emissions | 5 | 10 | 15 |
2 | pakistan | fertility rate | 1 | 2 | 1 |
3 | pakistan | CO2 emissions | NaN | NaN | NaN |
DF 我要:
id| country | year | fertility rate | CO2 emissions
--+----------+------+----------------+---------
0 | saudi | 2015 | 1 | 5
1 | saudi | 2016 | 2 | 10
2 | saudi | 2017 | 2 | 15
3 | pakistan | 2015 | 1 | NaN
4 | pakistan | 2016 | 2 | NaN
5 | pakistan | 2017 | 1 | NaN
我尝试了多种不同的熔体配置,但不知何故我无法解决这个问题。
IIUC melt
+ pivot_table
。此答案假定 id
是您的索引。如果不是,就放弃吧,因为计算中不需要它。
d = df.melt(id_vars=["country", "series name"], var_name="year")
d.pivot_table(
index=["country", "year"], columns="series name", values="value"
).reset_index()
series name country year CO2 emissions fertility rate
0 pakistan 2015 NaN 1.0
1 pakistan 2016 NaN 2.0
2 pakistan 2017 NaN 1.0
3 saudi 2015 5.0 1.0
4 saudi 2016 10.0 2.0
5 saudi 2017 15.0 2.0
我知道,这个问题已经被问过好几次了,但我没能根据已经问过的问题来构建我的解决方案。
DF 我有:
id| country | series name | 2015 | 2016 | 2017
--+----------+----------------+------+------+------
0 | saudi | fertility rate | 1 | 2 | 2 |
1 | saudi | CO2 emissions | 5 | 10 | 15 |
2 | pakistan | fertility rate | 1 | 2 | 1 |
3 | pakistan | CO2 emissions | NaN | NaN | NaN |
DF 我要:
id| country | year | fertility rate | CO2 emissions
--+----------+------+----------------+---------
0 | saudi | 2015 | 1 | 5
1 | saudi | 2016 | 2 | 10
2 | saudi | 2017 | 2 | 15
3 | pakistan | 2015 | 1 | NaN
4 | pakistan | 2016 | 2 | NaN
5 | pakistan | 2017 | 1 | NaN
我尝试了多种不同的熔体配置,但不知何故我无法解决这个问题。
IIUC melt
+ pivot_table
。此答案假定 id
是您的索引。如果不是,就放弃吧,因为计算中不需要它。
d = df.melt(id_vars=["country", "series name"], var_name="year")
d.pivot_table(
index=["country", "year"], columns="series name", values="value"
).reset_index()
series name country year CO2 emissions fertility rate
0 pakistan 2015 NaN 1.0
1 pakistan 2016 NaN 2.0
2 pakistan 2017 NaN 1.0
3 saudi 2015 5.0 1.0
4 saudi 2016 10.0 2.0
5 saudi 2017 15.0 2.0