从pandas到字典,以便第一列中的值将成为键,第二列中的相应值将全部在列表中

时间:2017-03-21 19:55:47

标签: python pandas dictionary

我有一个非常大的pandas DataFrame,如下所示:

        t   gid
0   2010.0  67290
1   2020.0  92780
2   2040.0  92780
3   2060.0  92780
4   2090.0  92780
5   2110.0  92780
6   2140.0  92780
7   2190.0  92780
8   2010.0  69110
9   2010.0  78420
10  2020.0  78420
11  2020.0  78420
12  2030.0  78420
13  2040.0  78420

我希望将它翻译成字典,以便我得到:

gid_to_t [gid] ==所有t的列表,

例如 - gid_to_t [92778] == [2020,2040,2060,2090,2110 ...]

我知道我可以做到以下几点:

gid_to_t = {}
for i,gid in enumerate(list(sps.gid)):
    gid_to_t[gid] = list(sps[sps.gid==gid].t)

但这需要太长时间,我很乐意找到更快捷的方式。

由于

2 个答案:

答案 0 :(得分:2)

尝试to_dict dictionary Series创建的list创建#if necessary convert column to int df.t = df.t.astype(int) d = df.groupby('gid')['t'].apply(list).to_dict() print (d) {92780: [2020, 2040, 2060, 2090, 2110, 2140, 2190], 67290: [2010], 78420: [2010, 2020, 2020, 2030, 2040], 69110: [2010]} print (d[78420]) [2010, 2020, 2020, 2030, 2040]

{{1}}

答案 1 :(得分:0)

另一个不使用的答案适用。

d = {name: group.tolist() for name, group in df.groupby('gid')['t']}

{67290: [2010.0],
 69110: [2010.0],
 78420: [2010.0, 2020.0, 2020.0, 2030.0, 2040.0],
 92780: [2020.0, 2040.0, 2060.0, 2090.0, 2110.0, 2140.0, 2190.0]}