Ple*_*try 2 python dataframe python-3.x pandas
我有以下熊猫数据框:
Person Item1 Item2 Item3 Item4
Adam Apple Eggs Cookie
Alex Chocolate Orange Eggs Potato
Gina Eggs Apple Orange Milk
Run Code Online (Sandbox Code Playgroud)
我想把它转换成这样:
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
Run Code Online (Sandbox Code Playgroud)
我在发布之前已经彻底搜索了我的查询,但没有找到任何匹配项(也许有更好的方法来重新表述我的问题)。如果这是重复的,我很抱歉,但如果是,请引导我到以前回答过这个问题的地方。
首先用于melt重塑:
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
Run Code Online (Sandbox Code Playgroud)
然后聚合lists的自定义函数GroupBy.size,然后DataFrame通过构造函数创建新函数并join计算列:
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
Run Code Online (Sandbox Code Playgroud)