我有以下 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/