更改DataFrame Pivot_table标头以将其保存在Excel文件中
旋转数据框后,我在数据框架中有一个嵌套的听觉器,我想使其平坦,每个行上都有重复的项目(例如在Excel中) 你可以帮我吗?
import pandas as pd
data = {
"year": [2022, 2022 , 2021 , 2021 , 2020 ],
"client": ["A", "B", "B", "C", "C"],
"product" : [ "P1", "P2" , "P1", "P2", "P1"],
"sales" : [ 10,20, 20, 22, 25]
}
df = pd.DataFrame(data)
df2 = df.pivot_table ( index = ["year","client"] , columns = ["product"] , values = ["sales"] , aggfunc ="sum")
df2
sales
product P1 P2
year client
2020 C 25.0 NaN
2021 B 20.0 NaN
C NaN 22.0
2022 A 10.0 NaN
B NaN 20.0
我想在哪里获得平坦的标题和拔出的行:
year client P1 P2
2020 C 25.0 NaN
2021 B 20.0 NaN
2021 C NaN 22.0
2022 A 10.0 NaN
2022 B NaN 20.0
非常感谢
Nico
I have a nested hearders in a dataframe after pivoting it and I'd like to make it flat, with repeated item on each rows (like in a excel)
May you help me ?
import pandas as pd
data = {
"year": [2022, 2022 , 2021 , 2021 , 2020 ],
"client": ["A", "B", "B", "C", "C"],
"product" : [ "P1", "P2" , "P1", "P2", "P1"],
"sales" : [ 10,20, 20, 22, 25]
}
df = pd.DataFrame(data)
df2 = df.pivot_table ( index = ["year","client"] , columns = ["product"] , values = ["sales"] , aggfunc ="sum")
df2
sales
product P1 P2
year client
2020 C 25.0 NaN
2021 B 20.0 NaN
C NaN 22.0
2022 A 10.0 NaN
B NaN 20.0
where I'd like to get a flat header and reapeated rows :
year client P1 P2
2020 C 25.0 NaN
2021 B 20.0 NaN
2021 C NaN 22.0
2022 A 10.0 NaN
2022 B NaN 20.0
many thanks
Nico
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要使用
droplevel(0)
,该将删除顶级(销售)。设置columns.name
<代码>无将删除products
。因此,在创建df2
之后,添加以下行...You need to use
droplevel(0)
which will remove the top level (Sales). Settingcolumns.name
toNone
will remove theProducts
. So, afterdf2
is created, add these lines...您可以尝试
You can try