我有一个大约有 100M 行的数据框,(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
版本并从数据帧的长度中减去 -
len(df)-np.unique(df.id.values[::-1], return_index=1)[1]-1
二。对于 id
col 已经排序
方法 #2-A 我们可以使用 切片
来显着提高性能,因为我们可以避免排序 -
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]
sample 运行-
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
关于python - Pandas => 按组获取第一个和最后一个元素的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47115448/