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]}