Pandas将具有多个值的行数据合并到列的Python列表中

时间:2017-09-18 09:20:48

标签: python list pandas dataframe merge

我的数据框看起来像

DATA

*id*,             *name*,                      *URL*,                 *Type*  
    2,             birth_france_by_region,    http://abc. com,       T1 
    2,             birth_france_by_region,    http://pt. python,     T2 
    3,             long_lat,                  http://abc. com,       T3 
    3,             long_lat,                  http://pqur. com,      T1 
    4,             random_time_series,        http://sadsdc. com,    T2 
    4,             random_time_series,        http://sadcadf. com,   T3
    5,             birth_names,               http://google. com,    T1 
    5,             birth_names,               http://helloworld. com,T2 
    5,             birth_names,               http://hu. com,        T3

我希望此数据框合并id相等的行,并列出类型 网址的相应列表 所以最终输出应该像

*id*, *name*,             *URL*,                               *Type*  
2,birth_france_by_region,  [http://abc .com,http://pt.python], [T1,T2] 
3,long_lat,           [http://abc .com,http://pqur. com],       [T3,T1] 
4,random_time_series, [http://sadsdc. com,http://sadcadf .com,],[T2,T3] 
5,birth_names,        [http://google .com,http://helloworld. com,
                                       http://hu. com] ,   [T1,T2,T3]

2 个答案:

答案 0 :(得分:3)

我认为您需要groupby并汇总tuple,然后转换为list

df = df.groupby(['id','name']).agg(lambda x: tuple(x)).applymap(list).reset_index()

print (df)
   id                    name  \
0   2  birth_france_by_region   
1   3                long_lat   
2   4      random_time_series   
3   5             birth_names   

                                                 URL          Type  
0                 [http://abc.cm, http://pt.python]      [T1, T2]  
1                  [http://abc.cm, http://pqur.com]      [T3, T1]  
2            [http://sadsdc.com, http://sadcadf.com]      [T2, T3]  
3  [http://google.;com, http://helloworld.com, ht...  [T1, T2, T3] 

因为版本0.20.3引发错误:

df = df.groupby(['id','name']).agg(lambda x: x.tolist())
  

ValueError:函数不会减少

答案 1 :(得分:0)

这将为您提供" URL"的预期结果。柱:

test.groupby(["id", "name"])['URL'].apply(list)

id  name                  
2   birth_france_by_region                 [http://abc. com, http://pt. python]
3   long_lat                                [http://abc. com, http://pqur. com]
4   random_time_series                [http://sadsdc. com, http://sadcadf. com]
5   birth_names               [http://google. com, http://helloworld. com, h...

但是,我无法找到网址和类型列的解决方案。

我可以建议分两步完成:

  • temp_table1 = test.groupby(["id", "name"])['URL'].apply(list)
  • temp_table2 = test.groupby(["id", "name"])['Type'].apply(list)
  • 合并temp_table1& temp_table2