Python 3.x 在python中如何将多列放入键值列表 我有一个下面的数据框,我想使用数据框中的列在列表中创建一个键值对,我如何在python中做到这一点。 我想创建一个新的数据框,如下所示: defaultdict groupby defaultdict group

Python 3.x 在python中如何将多列放入键值列表 我有一个下面的数据框,我想使用数据框中的列在列表中创建一个键值对,我如何在python中做到这一点。 我想创建一个新的数据框,如下所示: defaultdict groupby defaultdict group,python-3.x,pandas,dataframe,Python 3.x,Pandas,Dataframe,在python中如何将多列放入键值列表 我有一个下面的数据框,我想使用数据框中的列在列表中创建一个键值对,我如何在python中做到这一点。 我想创建一个新的数据框,如下所示: defaultdict groupby defaultdict groupby df= city code qty1 type hyd 1 10 a hyd 2

在python中如何将多列放入键值列表 我有一个下面的数据框,我想使用数据框中的列在列表中创建一个键值对,我如何在python中做到这一点。 我想创建一个新的数据框,如下所示:
defaultdict

groupby
defaultdict

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