gpt4 book ai didi

python-3.x - Pandas 数据框,但添加看不见的值

转载 作者:行者123 更新时间:2023-12-04 08:31:19 24 4
gpt4 key购买 nike

我有 2 个数据框:

purchases = pd.DataFrame([['Alice', 'sweeties', 4],
['Bob', 'chocolate', 5],
['Alice', 'chocolate', 3],
['Claudia', 'juice', 2]],
columns=['client', 'item', 'quantity'])

goods = pd.DataFrame([['sweeties', 15],
['chocolate', 7],
['juice', 8],
['lemons', 3]], columns=['good', 'price'])
我想在这张照片中使用 cols 和 index 来转换购买:
enter image description here
我的第一个想法是使用枢轴:
purchases.pivot(columns="item", values="quantity")
输出:
enter image description here
问题是:我还需要枢轴结果中的柠檬列,因为它存在于商品数据框中(仅填充了 None 值)。
我怎样才能做到这一点?

最佳答案

您可以链接 reindex :

purchases.pivot(columns="item", values="quantity").reindex(goods['good'], axis=1)
输出:
good  sweeties  chocolate  juice  lemons
0 4.0 NaN NaN NaN
1 NaN 5.0 NaN NaN
2 NaN 3.0 NaN NaN
3 NaN NaN 2.0 NaN

关于python-3.x - Pandas 数据框,但添加看不见的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65010932/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com