Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 基于字典和索引列表从列中获取值列表_Python_Pandas_List_Dictionary_Pandas Groupby - Fatal编程技术网

Python 基于字典和索引列表从列中获取值列表

Python 基于字典和索引列表从列中获取值列表,python,pandas,list,dictionary,pandas-groupby,Python,Pandas,List,Dictionary,Pandas Groupby,我有以下数据帧: >>> price code 1695 765 0 1700 854 1 1702 975 0 1703 452 0 1704 275 0 ... 2169 754 14 2174 743 14 2181 932 15 我想创建字典,代码作为键,价格作为值。 我尝试过这样做: groups=

我有以下数据帧:

>>>      price    code
1695     765       0
1700     854       1
1702     975       0
1703     452       0
1704     275       0
...
2169     754      14
2174     743      14
2181     932      15
我想创建字典,代码作为键,价格作为值。 我尝试过这样做:

groups=df.groupby('code').groups
groups
>>>{0:[1695,1702,1703,1704], 1:[1700,...]...,14:[2169,2174],15:[2181]}
我试图在groupby中定义price列,但这将过程添加到键而不是值列表中,因此类似于{(0765):[1695],(0975):[1702]…}

我没有看到太多关于分组方法的信息

我想要的iutput如下所示:

{0 : [ 765,975,452,275],1:[854],...,14:[754,743],15:[932]}

首先聚合
列表
s,然后转换为
dict

d = df.groupby('code')['price'].agg(list).to_dict()
或使用听写理解:

d = {k: list(v['price']) for k, v in df.groupby('code')}
#similar alternative
d = {k: list(v) for k, v in df.groupby('code')['price']}

print (d)
0: [765, 975, 452, 275], 1: [854], 14: [754, 743], 15: [932]}