慕田峪4524236
DataFrame.groupby您可以创建由with apply、 thenSeries.to_frame和 last列表填充的嵌套字典DataFrame.to_dict:d = df.groupby('line')['stop'].apply(list).to_frame().to_dict('index')print (d){1: {'stop': ['1_a', '1_b', '1_c']}, 2: {'stop': ['2_a', '2_c']}}如果需要通过某些分隔符连接值,例如,:d1 = df.groupby('line')['stop'].apply(','.join).to_frame().to_dict('index')print (d1){1: {'stop': '1_a,1_b,1_c'}, 2: {'stop': '2_a,2_c'}}编辑:GroupBy.agg带有和 省略的多列的解决方案to_frame():print (df) line stop lat lon0 1 1_a 2 21 1 1_b 3 12 1 1_c 4 33 2 2_a 5 64 2 2_c 6 6d = df.groupby('line')[['stop','lat','lon']].agg(list).to_dict('index')print (d){1: {'stop': ['1_a', '1_b', '1_c'], 'lat': [2, 3, 4], 'lon': [2, 1, 3]}, 2: {'stop': ['2_a', '2_c'], 'lat': [5, 6], 'lon': [6, 6]}}
DIEA
您可以避免该to_dict部分并迭代分组以获取字典,因为您没有进行任何计算:{key: {"stops": ",".join(value.stop.array)} for key, value in df.groupby("line")}{1: {'stops': '1_a,1_b,1_c'}, 2: {'stops': '2_a,2_c'}}或者您可以将子值保留为列表:{key: {"stops": list(value.stop.array)} for key, value in df.groupby("line")}{1: {'stops': ['1_a', '1_b', '1_c']}, 2: {'stops': ['2_a', '2_c']}}