gpt4 book ai didi

python - 转置/反转 pandas 数据框的最简单方法是什么?

转载 作者:行者123 更新时间:2023-12-03 08:59:30 29 4
gpt4 key购买 nike

我有以下 pandas 数据框:

Person     Item1      Item2     Item3     Item4
Adam Apple Eggs Cookie
Alex Chocolate Orange Eggs Potato
Gina Eggs Apple Orange Milk

我想把它转换成这样:

Item      Count     Person1     Person2     Person3
Apple 2 Adam Gina
Eggs 3 Adam Alex Gina
Cookie 1 Adam
Chocolate 1 Alex
Orange 2 Alex Gina
Potato 1 Alex
Milk 1 Gina

我在发布之前已经彻底搜索了我的查询,但我没有找到任何匹配项(也许有更好的方法来重新表述我的问题)。如果这是重复的,我很抱歉,但如果是,请引导我到以前回答过这个问题的地方。

最佳答案

使用melt首先 reshape :

df = df.melt('Person', value_name='Item')
print (df)
Person variable Item
0 Adam Item1 Apple
1 Alex Item1 Chocolate
2 Gina Item1 Eggs
3 Adam Item2 Eggs
4 Alex Item2 Orange
5 Gina Item2 Apple
6 Adam Item3 Cookie
7 Alex Item3 Eggs
8 Gina Item3 Orange
9 Adam Item4 NaN
10 Alex Item4 Potato
11 Gina Item4 Milk

然后使用 GroupBy.size 聚合列表的自定义函数然后通过构造函数和join创建新的DataFrame计数列:

f = lambda x: x.tolist()
f.__name__ = 'Person'
df1 = df.groupby('Item', sort=False)['Person'].agg([f, 'size'])

df2 = pd.DataFrame(df1.pop('Person').values.tolist(), index=df1.index).add_prefix('Person')
df3 = df1.join(df2).reset_index()
print (df3)
Item size Person0 Person1 Person2
0 Apple 2 Adam Gina None
1 Chocolate 1 Alex None None
2 Eggs 3 Gina Adam Alex
3 Orange 2 Alex Gina None
4 Cookie 1 Adam None None
5 Potato 1 Alex None None
6 Milk 1 Gina None None

关于python - 转置/反转 pandas 数据框的最简单方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52053478/

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