How can I get a previous row from where the condition is met in data frame in Pandas

无人久伴 提交于 2021-02-07 12:33:18

问题


For instance, I have a data frame below, I want to get the timestamp from the previous row where the Value is 1

    TIME    VALUE
0   23:01   0
1   23:02   0
2   23:03   1
3   23:04   0
4   23:05   0
5   23:06   1
6   23:07   0
7   23:08   0
8   23:09   0
9   23:10   0
10  23:11   1
11  23:12   0
12  23:13   0
13  23:14   0
14  23:15   0
15  23:16   1

I want to get the following as an output

    PREV_TIME
0   23:02
1   23:05
2   23:10
3   23:15

I don't know where to put shift(1) in the following

PREV_TIME = df['Time'][(df.Value == 1)]

回答1:


Call shift on 'VALUE' column and pass this as the condition:

In [7]:
df.loc[df['VALUE'].shift(-1)==1, 'TIME']

Out[7]:
1     23:02
4     23:05
9     23:10
14    23:15
Name: TIME, dtype: object

To add a new column 'PREV Time' alongside the row where the condition is met:

In [21]:
df['Prev_Time'] = df.loc[df['VALUE'].shift(-1)==1, 'TIME']
df['Prev_Time'] = df['Prev_Time'].shift()
df

Out[21]:
     TIME  VALUE Prev_Time
0   23:01      0       NaN
1   23:02      0       NaN
2   23:03      1     23:02
3   23:04      0       NaN
4   23:05      0       NaN
5   23:06      1     23:05
6   23:07      0       NaN
7   23:08      0       NaN
8   23:09      0       NaN
9   23:10      0       NaN
10  23:11      1     23:10
11  23:12      0       NaN
12  23:13      0       NaN
13  23:14      0       NaN
14  23:15      0       NaN
15  23:16      1     23:15


来源:https://stackoverflow.com/questions/36339679/how-can-i-get-a-previous-row-from-where-the-condition-is-met-in-data-frame-in-pa

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!