如何从 Pandas 的数据框中满足条件的位置获取前一行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36339679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 00:58:05  来源:igfitidea点击:

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

pythonpandas

提问by wafers

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

例如,我在下面有一个数据框,我想从值为 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

我不知道把shift(1)下面的放在哪里

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

回答by EdChum

Call shifton 'VALUE' column and pass this as the condition:

调用shift“VALUE”列并将其作为条件传递:

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:

在满足条件的行旁边添加一个新列“PREV Time”:

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