如何使多列成为python中的键值列表

时间:2018-10-08 20:34:21

标签: python-3.x pandas dataframe

我有一个下面的数据框,我想使用数据框中的列在列表中创建一个键值对,我该如何在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"}]

1 个答案:

答案 0 :(得分:2)

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