简体   繁体   English

将pandas数据帧转换为键值对列表

[英]Converting pandas dataframe to list of key value pairs

I have a pandas dataframe as below: 我有一个pandas数据帧如下:

 col1 col2 
0  a     11
1  b     12
2  b     13
3  a     14
4  a     15 

and I want to convert it into a list which should be like 我想把它转换成一个应该是的列表

myList = {'a':['11','14','15'],'b':['12','13']}

Please suggest how to do it? 请建议怎么做?

Group by the first column, collect the values of the second column into lists, convert the result into a dictionary: 按第一列分组,将第二列的值收集到列表中,将结果转换为字典:

df.groupby('col1')['col2'].apply(list).to_dict()
#{'a': ['11', '14', '15'], 'b': ['12', '13']}

Solution from itertools 来自itertools解决方案

import itertools

l=df.sort_values('col1').values.tolist()
{k: [x[1] for x in g] for k, g in itertools.groupby(l,lambda x : x[0])}
{'a': [11, 14, 15], 'b': [12, 13]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM