如果最后n行为True,则将Python数据框设置为True [英] Python Dataframe Set True if last n rows are True
本文介绍了如果最后n行为True,则将Python数据框设置为True的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个新列,其中如果最后n行在其他列中为True,则为True。它可以按照我的要求完美运行。问题是这要花费很多时间。
I want to create a new column where in, True if last n rows are True in other column. It is running perfectly as I wanted. The problem is it is taking lot of time.
dfx = pd.DataFrame({'A':[False,False,False,False,True,True,True,True,False,True]})
n=2 ## n to cover 10 min range samples
cl_id = dfx.columns.tolist().index('A') ### cl_id for index number of the column for using in .iloc
l1=[False]*n+[all(dfx.iloc[x+1-n:x+1,cl_id].tolist()) for x in np.arange(n,len(dfx))]
dfx['B'] = l1
print(dfx)
#old_col # New_col
A B
0 False False
1 False False
2 False False
3 False False
4 True False
5 True True ## Here A col last two rows True, hence True
6 True True ## Here A col last two rows True, hence True
7 True True ## Here A col last two rows True, hence True
8 False False
9 True False
有没有更好的方法。运行并提供输出会花费很多时间。
Is there a better way of doing it. It is taking lot of time to run and provide the output.
推荐答案
使用 pandas.Series.rolling
:
n = 2
dfx["A"].rolling(n).sum().eq(n)
输出:
0 False
1 False
2 False
3 False
4 False
5 True
6 True
7 True
8 False
9 False
Name: A, dtype: bool
针对OP的基准快1000倍):
Benchmark against OP (about 1000x faster):
dfx = pd.DataFrame({'A':[False,False,False,False,True,True,True,True,False,True]*1000})
%timeit -n10 l1 = dfx["A"].rolling(n).sum().eq(n)
# 702 µs ± 88.6 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit -n10 l2 = [False]*n+[all(dfx.iloc[x+1-n:x+1,cl_id].tolist()) for x in np.arange(n,len(dfx))]
# 908 ms ± 24 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
l1.tolist() == l2
# True
这篇关于如果最后n行为True,则将Python数据框设置为True的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文