python - Pandas Dataframe 合并列上的行以形成字典列表

标签 python python-2.7 pandas dataframe

我有一个看起来像这样的数据框

数据

*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 相等的行,并将字典的 Type 列表作为字典 URL 的键作为值 所以最终输出是这样的:-

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

最佳答案

使用groupby具有自定义功能:

df = (df.groupby([df['id'],df['name']])
       .apply(lambda x: [{k:v} for k, v in zip(x['Type'], x['URL'])])
       .reset_index(name='URL'))
print (df)
   id                    name  \
0   2  birth_france_by_region   
1   3                long_lat   
2   4      random_time_series   
3   5             birth_names   

                                                 URL  
0  [{'T1': 'http://abc. com'}, {'T2': 'http://pt....  
1  [{'T3': 'http://abc. com'}, {'T1': 'http://pqu...  
2  [{'T2': 'http://sadsdc. com'}, {'T3': 'http://...  
3  [{'T1': 'http://google. com'}, {'T2': 'http://...  

关于python - Pandas Dataframe 合并列上的行以形成字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46539405/

相关文章:

python - pandas groupby 日期选择每天最早的

python - 无法安装最新版本的 pandas (1.0.3)

python - 如何设置 Pandas DataFrame 左上角单元格的样式

python - 如何统计一列中的元素并将结果作为新列?

python - 相当于python ctypes的C dll

python - 我正在尝试从 Django 内运行一个无尽的工作线程(守护进程)

python - 在数据库中搜索第二天格式

python:双端队列与列表性能比较

python - 创建一个数字序列并在达到特定数字时重置自身

python - 如何在 Linux 中使用 PyInstaller 编译 python