背景和研究
我目前正在试验 pivot_table来自 Pandas 图书馆,正在寻找一种以某种特定方式制作表格的方法。 这个想法是根据索引在行中呈现值,在列中呈现另一个变量的值。
看了several之后answers on the site与 pandas.pivot_table 中的分组有关,但是到目前为止我还没有找到可以解决该问题的方法。
代码和示例
由于展示胜于讲述,我为您提供了一个简短的代码片段来展示我设法做到的事情。
import pandas as pd
df = pd.DataFrame(
{
"Year": [2018, 2018, 2018, 2018, 2018, 2018, 2018, 2019, 2019, 2019, 2019, 2019, 2019, 2019],
"Month": [4, 5, 6 , 7, 8, 9, 10, 4, 5, 6 , 7, 8, 9, 10],
"Apples": [3, 5, 1, 2, 5, 6, 6, 8, 9, 9, 1, 8, 6, 4],
"Temperature": [8.6, 13.7, 16.5, 18.5, 18.0, 13.5, 8.7, 9.2 , 14.2, 15.5, 20.1, 18.6, 12.8, 8.7]
}
)
pivoted_data = pd.pivot_table(df, index=['Month'], columns=['Year'], values=['Apples', 'Temperature']).transpose()
数据透视表的结果:
Month 4 5 6 7 8 9 10
Year
Apples 2018 3.0 5.0 1.0 2.0 5.0 6.0 6.0
2019 8.0 9.0 9.0 1.0 8.0 6.0 4.0
Temperature 2018 8.6 13.7 16.5 18.5 18.0 13.5 8.7
2019 9.2 14.2 15.5 20.1 18.6 12.8 8.7
我做过的最好的尝试是对数据帧使用 .transpose() 方法并如上所述渲染表格,但这并不能完全实现我正在寻找的东西。
预期结果
我希望按如下方式呈现数据:
Month 4 5 6 7 8 9 10
Year
2018 Temperature 8.6 13.7 16.5 18.5 18.0 13.5 8.7
Apples 3.0 5.0 1.0 2.0 5.0 6.0 6.0
2019 Temperature 8.0 9.0 9.0 1.0 8.0 6.0 4.0
Apples 9.2 14.2 15.5 20.1 18.6 12.8 8.7
差异很小但非常重要,因为数据是按年份显示的(而不是按苹果和温度的值)。
我一直没有成功地解决当前问题。 有人知道如何以那种方式呈现这个小数据集吗?
最佳答案
使用DataFrame.swaplevel
与 DataFrame.sort_index
,转置的另一种解决方案是 DataFrame.T
(减少打字):
pivoted_data = (pd.pivot_table(df,
index='Month',
columns='Year',
values=['Apples', 'Temperature'])
.T
.swaplevel(1, 0)
.sort_index())
print (pivoted_data)
Month 4 5 6 7 8 9 10
Year
2018 Apples 3.0 5.0 1.0 2.0 5.0 6.0 6.0
Temperature 8.6 13.7 16.5 18.5 18.0 13.5 8.7
2019 Apples 8.0 9.0 9.0 1.0 8.0 6.0 4.0
Temperature 9.2 14.2 15.5 20.1 18.6 12.8 8.7
关于python - 如何制作一个数据透视表,其中的值按索引排列在行中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56663956/