如何使用groupby创建唯一的用户ID级别数据帧?

2024-10-01 05:00:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个ID Visit11 Visit12 Visit13 Visit14 Visit15的输入数据帧

1   Orange              
2   Orange              
2       Apple           
3   Grapes              
4   Apple               
5   Not Defined             
5       Apple           
6   Apple               
7   Banana              
7                   
7                   
7                   
7                   
7                   
7                   
8   Banana              
8       Apple           
8           Banana      
8               Apple   
8                   Banana
9                   
9                   
9                   
9   

我正在使用groupby获得预期的输出,但它将所有购买的内容都包含在一个单元格中。我想在不同的列中加入购买,其中一行代表一个用户。预期输出应为


    ID  Visit11 Visit12 Visit13 Visit1Int4  Visit15
1   Orange              
2   Orange  Apple           
3   Grapes              
4   Apple               
5   Not Defined Apple           
6   Apple               
7   Banana              
8   Banana  Apple   Banana  Apple   Banana
9                   

Tags: 数据id内容applenotbananagroupbyorange
1条回答
网友
1楼 · 发布于 2024-10-01 05:00:07

我相信你需要:

print (df)
   ID      Visit11 Visit12
0   1       Orange        
1   2               Orange
2   2        Apple        
3   3       Grapes        
4   4        Apple        
5   5  Not Defined        
6   5                Apple

df = df.replace('', np.nan)
df1 = df.set_index('ID').stack().unstack().sort_index(axis=1).reset_index().fillna('')
print (df1)
   ID      Visit11 Visit12
0   1       Orange        
1   2        Apple  Orange
2   3       Grapes        
3   4        Apple        
4   5  Not Defined   Apple

替代解决方案:

df = df.replace('', np.nan)
df1 = df.groupby('ID', as_index=False).first().fillna('')
print (df1)
   ID      Visit11 Visit12
0   1       Orange        
1   2        Apple  Orange
2   3       Grapes        
3   4        Apple        
4   5  Not Defined   Apple

相关问题 更多 >