use*_*204 4 numpy python-3.x pandas
我有一个熊猫数据框,如:
a b id
1 10 6 1
2 6 -3 1
3 -3 12 1 # First time id 1 has a b value over 10
4 4 23 2 # First time id 2 has a b value over 10
5 12 11 2
6 3 -5 2
Run Code Online (Sandbox Code Playgroud)
如何创建一个新的数据框,首先获取该id列,然后第一次获取该列b超过 10 的时间,以便结果如下所示:
a b id
1 -3 12 1
2 4 23 2
Run Code Online (Sandbox Code Playgroud)
我有一个包含 2,000,000 行和大约 10,000 个id值的数据框,因此 for 循环非常慢。
首先使用 fastboolean indexing进行过滤,然后使用groupby+ first:
df = df[df['b'] > 10].groupby('id', as_index=False).first()
print (df)
id a b
0 1 -3 12
1 2 4 23
Run Code Online (Sandbox Code Playgroud)
如果在某些组中没有更大的值,解决方案有点复杂10- 需要扩展掩码duplicated:
print (df)
a b id
1 7 6 3 <- no value b>10 for id=3
1 10 6 1
2 6 -3 1
3 -3 12 1
4 4 23 2
5 12 11 2
6 3 -5 2
mask = ~df['id'].duplicated(keep=False) | (df['b'] > 10)
df = df[mask].groupby('id', as_index=False).first()
print (df)
id a b
0 1 -3 12
1 2 4 23
2 3 7 6
Run Code Online (Sandbox Code Playgroud)
时间:
#[2000000 rows x 3 columns]
np.random.seed(123)
N = 2000000
df = pd.DataFrame({'id': np.random.randint(10000, size=N),
'a':np.random.randint(10, size=N),
'b':np.random.randint(15, size=N)})
#print (df)
In [284]: %timeit (df[df['b'] > 10].groupby('id', as_index=False).first())
10 loops, best of 3: 67.6 ms per loop
In [285]: %timeit (df.query("b > 10").groupby('id').head(1))
10 loops, best of 3: 107 ms per loop
In [286]: %timeit (df[df['b'] > 10].groupby('id').head(1))
10 loops, best of 3: 90 ms per loop
In [287]: %timeit df.query("b > 10").groupby('id', as_index=False).first()
10 loops, best of 3: 83.3 ms per loop
#without sorting a bit faster
In [288]: %timeit (df[df['b'] > 10].groupby('id', as_index=False, sort=False).first())
10 loops, best of 3: 62.9 ms per loop
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1108 次 |
| 最近记录: |