如何在 Python 中将多个列制作成键值列表



我有一个下面的数据框,我想使用数据框中的列在列表中创建一个键值对,如何在python中做到这一点。

df=
city    code     qty1       type
hyd     1        10          a
hyd     2        12          b
ban     2        15          c 
ban     4        25          d     
pune    1        10          e
pune    3        12          f

我想创建一个新的数据框,如下所示:

df1 = 
city                list
hyd      [{"1":"10","type":"a"},{"2":"12","type":"b"}]
ban      [{"2":"15","type":"c"},{"4":"25","type":"d"}]
pune     [{"1":"10","type":"e"},{"3":"12","type":"f"}]

defaultdict

from collections import defaultdict
d = defaultdict(list)
for t in df.itertuples():
d[t.city].append({t.code: t.qty1, 'type': t.type})
pd.Series(d).rename_axis('city').to_frame('list')
list
city                                              
ban   [{2: 15, 'type': 'c'}, {4: 25, 'type': 'd'}]
hyd   [{1: 10, 'type': 'a'}, {2: 12, 'type': 'b'}]
pune  [{1: 10, 'type': 'e'}, {3: 12, 'type': 'f'}]

groupby

pd.Series([
{c: q, 'type': t}
for c, q, t in zip(df.code, df.qty1, df.type)
]).groupby(df.city).apply(list).to_frame('list')
list
city                                              
ban   [{2: 15, 'type': 'c'}, {4: 25, 'type': 'd'}]
hyd   [{1: 10, 'type': 'a'}, {2: 12, 'type': 'b'}]
pune  [{1: 10, 'type': 'e'}, {3: 12, 'type': 'f'}]

最新更新