这不一定是最优雅的,但它是有效的:找到任何一点
motion
是
1
,或在何处
运动
向任一方向移动1是
一
. 有两种方法
numpy
功能(注意
麻木的
函数不需要显式导入
麻木的
,因为它们也内置在
pandas
可以通过
pd.np
,但请参见@abhi的评论
熊猫
等效值):
df['motion2'] = pd.np.where(df.motion.values|pd.np.roll(df.motion.values,1)|pd.np.roll(df.motion.values,-1),1,0)
# The following is Essentially the equivalent, but maybe a bit clearer / more efficient
df['motion2'] = pd.np.stack((df.motion.values,pd.np.roll(df.motion.values,1),pd.np.roll(df.motion.values,-1))).any(0).astype(int)
>>> df
device time motion motion2
0 1 1 0 0
1 1 2 0 1
2 1 3 1 1
3 1 4 1 1
4 1 5 1 1
5 1 6 0 1
6 1 7 0 0
7 1 8 0 1
8 1 9 1 1
9 1 10 1 1
10 1 11 0 1
11 1 12 0 0
12 2 5 0 0
13 2 6 0 0
14 2 7 0 1
15 2 8 1 1
16 2 9 1 1
17 2 10 1 1
18 2 11 0 1
19 2 12 1 1
20 2 13 0 1
21 2 14 0 0