我有一个大约有1亿行的数据帧(内存为1.4Gb)
给定输入:
df.head()
Out[1]:
id term x
0 1 A 3
1 1 B 2
2 2 A 1
3 2 B 1
4 2 F 1
5 2 G 1
6 2 Z 1
7 3 K 1
8 3 M 1
9 3 N 1
10 3 Q 1
11 3 R 1
12 3 Z 1
13 4 F 1
我想为每个ID检索第一行的索引。例:
Out[1]:
id first_idx
0 1 0
1 2 2
2 3 7
2 4 13
我当前的方法非常慢:
first_row = {}
last_id = None
first_row = None
#iterate over all rows
for idx,r in bow.iterrows():
cid = r['id']
if cid != last_id: #is this an ID we haven't seen before?
first_row[cid] = idx
last_id = cid
任何建议都会有很大帮助。
方法#1使用np.unique
-
idx = np.unique(df.id.values, return_index=1)[1]
要获取每个的最后一个索引ID
,只需使用flipped
version并从数据帧的长度中减去-
len(df)-np.unique(df.id.values[::-1], return_index=1)[1]-1
id
col已经被排序方法#2-A我们可以使用slicing
显着的性能提升,因为我们会避免排序-
a = df.id.values
idx = np.concatenate(([0],np.flatnonzero(a[1:] != a[:-1])+1))
方法#2-B使用masking
(最好使用大量ID号)
a = df.id.values
mask = np.concatenate(([True],a[1:] != a[:-1]))
idx = np.flatnonzero(mask)
对于最后一个索引:
np.flatnonzero(np.concatenate((a[1:] != a[:-1],[True])))
方法#3对于序号,我们可以使用np.bincount
-
a = df.id.values
idx = np.bincount(a).cumsum()[:-1]
样品运行-
In [334]: df
Out[334]:
id term x
0 1 A 3
1 1 B 2
2 2 A 1
3 2 B 1
4 2 F 1
5 2 G 1
6 2 Z 1
7 3 K 1
8 3 M 1
9 3 N 1
10 3 Q 1
11 3 R 1
12 3 Z 1
13 4 F 1
In [335]: idx = np.unique(df.id.values, return_index=1)[1]
In [336]: idx
Out[336]: array([ 0, 2, 7, 13])
如果您需要在数据框中输出-
In [337]: a = df.id.values
In [338]: pd.DataFrame(np.column_stack((a[idx], idx)), columns=[['id','first_idx']])
Out[338]:
id first_idx
0 1 0
1 2 2
2 3 7
3 4 13
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句