![](/img/trans.png)
[英]Pandas select rows when column value within range from another row column value with group filter
[英]Pandas select rows when column value within range from another row column value
我正在嘗試使用以下格式從dataframe(100k-500k行)創建子集
d = {'time':[1,2,3,5,7,9,9.5,10], 'val':['match','match','match','not','not','match','match','match']}
df = pd.DataFrame(d)
time val
0 1.0 match
1 2.0 match
2 3.0 match
3 5.0 not
4 7.0 not
5 9.0 match
6 9.5 match
7 10.0 match
我想在時間在有限范圍內時選擇包含所有行的子集。 例如,如果range <= 1,則選擇第一行和最后三行
我想要的輸出:
time val
0 1.0 match
1 2.0 match
2 3.0 match
5 9.0 match
6 9.5 match
7 10.0 match
在一行中它看起來像這樣:
df.loc[(df['time'].diff()<=1)|(df['time'].diff(-1)>=-1)]
我有一個解決方案,但我認為這不是最好的解決方案
dfasc=df.sort_values(['time'], ascending=1)
dfdesc=df.sort_values(['time'], ascending=0)
print (df[(dfasc['time'].diff()<=1.0) | (dfdesc['time'].diff()>=-1.0)])
time val
0 1.0 match
1 2.0 match
2 3.0 match
5 9.0 match
6 9.5 match
7 10.0 match
如果你想這樣做它是矢量化的,這將是有效的。 您可能希望使用矢量化操作,因為您的DF太大了。 你可能還想把它放到一個函數來節省內存,因為我在下面做了一些變量。
import numpy as np
import pandas as pd
df = pd.DataFrame({'time':[1,2,2.5,3,9,9.5,10,11,12],'val':
['not','match','match','match','match','match','match','not','not']})
'''
df
time val
0 1.0 not
1 2.0 match
2 2.5 match
3 3.0 match
4 9.0 match
5 9.5 match
6 10.0 match
7 11.0 not
8 12.0 not
'''
x = df.time.values
tmp = (x[1:] - x[:-1]) < 1
fst = tmp[0]
lst = tmp[-1]
mid = np.any([tmp[1:],tmp[:-1]],axis =0)
ans = np.concatenate([[fst],mid,[lst]])
df = df[ans]
''' Output
time val
1 2.0 match
2 2.5 match
3 3.0 match
4 9.0 match
5 9.5 match
6 10.0 match
'''
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.