熊猫df与groupby一起听歌

时间:2020-10-12 08:03:43

标签: python pandas dataframe dictionary

我有这个df:

public class MyMultiSelectListPreference extends MultiSelectListPreference {

    ...

    @Override
    protected void onDialogClosed(boolean positiveResult) {
        super.onDialogClosed(positiveResult);

        if (positiveResult == false) {
            // do something
        }
    }
}

我要创建以下字典:

line stop 1 1_a 1 1_b 1 1_c 2 2_a 2 2_c

有人知道如何使用d={1 : {"stops" : "1_a","1_b","1_c"}, 2 : {"stops" : "2_a","2_b","2_c"}}方法吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

您可以创建由DataFrame.groupbyapply然后是Series.to_frame和最后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  lon
0     1  1_a    2    2
1     1  1_b    3    1
2     1  1_c    4    3
3     2  2_a    5    6
4     2  2_c    6    6

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

答案 1 :(得分:1)

由于您没有进行任何计算,因此可以避免使用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']}}