Ale*_*vid 5 python optimization numpy dataframe pandas
我有一个大约有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
Run Code Online (Sandbox Code Playgroud)
我想为每个ID检索第一行的索引。例:
Out[1]:
id first_idx
0 1 0
1 2 2
2 3 7
2 4 13
Run Code Online (Sandbox Code Playgroud)
我当前的方法非常慢:
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
Run Code Online (Sandbox Code Playgroud)
任何建议都会有很大帮助。
方法 #1与np.unique
-
idx = np.unique(df.id.values, return_index=1)[1]
Run Code Online (Sandbox Code Playgroud)
要获取每个的最后一个索引ID
,只需使用flipped
version 并从数据帧的长度中减去 -
len(df)-np.unique(df.id.values[::-1], return_index=1)[1]-1
Run Code Online (Sandbox Code Playgroud)
id
已经排序的 col方法#2-A我们可以使用slicing
显着的性能提升,因为我们将避免排序 -
a = df.id.values
idx = np.concatenate(([0],np.flatnonzero(a[1:] != a[:-1])+1))
Run Code Online (Sandbox Code Playgroud)
方法#2-B with masking
(更适合大量身份证号码)
a = df.id.values
mask = np.concatenate(([True],a[1:] != a[:-1]))
idx = np.flatnonzero(mask)
Run Code Online (Sandbox Code Playgroud)
对于最后一个索引:
np.flatnonzero(np.concatenate((a[1:] != a[:-1],[True])))
Run Code Online (Sandbox Code Playgroud)
方法#3对于序列号,我们可以使用np.bincount
-
a = df.id.values
idx = np.bincount(a).cumsum()[:-1]
Run Code Online (Sandbox Code Playgroud)
样品运行 -
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])
Run Code Online (Sandbox Code Playgroud)
如果您需要数据帧中的输出 -
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
Run Code Online (Sandbox Code Playgroud)
df = df.index.to_series().groupby(df['id']).first().reset_index(name='x')
print (df)
id x
0 1 0
1 2 2
2 3 7
3 4 13
Run Code Online (Sandbox Code Playgroud)
如果还需要最后一个索引值:
df = df.index.to_series().groupby(df['id']).agg(['first','last']).reset_index()
print (df)
id first last
0 1 0 1
1 2 2 6
2 3 7 12
3 4 13 13
Run Code Online (Sandbox Code Playgroud)