我有一个非常大的数据帧,如下所示:
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 \u to \u t[92778]==[20202040206020910910…]
我知道我可以做到以下几点:
gid_to_t = {}
for i,gid in enumerate(list(sps.gid)):
gid_to_t[gid] = list(sps[sps.gid==gid].t)
但是时间太长了,我很乐意找到一个更快的方法。你知道吗
谢谢
编辑
我已经检查了评论中建议的方法,以下是数据: https://drive.google.com/open?id=1d3zUkc543hm8CZ_ZyzAzdbmQUE_G55bU
import pandas as pd
df1 = pd.read_pickle('stack.pkl')
%timeit -n 2 df1.groupby('gid')['t'].apply(list).to_dict()
2 loops, best of 3: 4.76 s per loop
%timeit -n 2 df1.groupby('gid')['t'].apply(lambda x: x.tolist()).to_dict()
2 loops, best of 3: 4.21 s per loop
%timeit -n 2 df1.groupby('gid', sort=False)['t'].apply(list).to_dict()
2 loops, best of 3: 4.84 s per loop
%timeit -n 2 {name: group.tolist() for name, group in df1.groupby('gid')['t']}
2 loops, best of 3: 4 s per loop
%timeit -n 2 {name: group.tolist() for name, group in df1.groupby('gid', sort=False)['t']}
2 loops, best of 3: 3.96 s per loop
%timeit -n 2 {name: group['t'].tolist() for name, group in df1.groupby('gid', sort=False)}
2 loops, best of 3: 7.16 s per loop
还有一个答案不适用。你知道吗
尝试从^{} 创建的
list
的Series
创建dictionary
:如果性能很重要,请将
sort=False
参数添加到groupby
:相关问题 更多 >
编程相关推荐