简体   繁体   English

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

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

For instance, I have a data frame below, I want to get the timestamp from the previous row where the Value is 1 例如,我有一个数据框,我想从上一行获取Value为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)]

Call shift on 'VALUE' column and pass this as the condition: 在“VALUE”列上调用shift并将其作为条件传递:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从 Pandas 数据框中满足条件的位置获取前一行 - How can I get a previous row from where the conditions are met in data frame in Pandas 如何从(切片)pandas 数据帧中的前一行获取值? - How to get a value from of the previous row in a (sliced) pandas data frame? 如何对熊猫数据框计算进行矢量化,如果不满足条件,则输入前一行的数据? - How to vectorize a pandas dataframe calculation where if a conditional is not met the data from the previous row is entered? 如果满足条件,如何用前一行替换 pandas 列行 - How to replace a pandas column row with the previous row if a condition is met 如何在 Pandas 的 DataFrame 中获取带有条件的前一行 - How to get previous row with condition in a DataFrame of Pandas 删除熊猫数据框中的行:每次满足特定条件时删除前k行 - Deleting rows in pandas data frame: Delete previous k rows each time a certain condition is met 在满足条件的地方添加列,但在pandas python中保留先前的值 - add columns where condition is met, but preserve previous value in pandas python Pandas DataFrame 在满足条件的前一行中查找最近的索引 - Pandas DataFrame find closest index in previous rows where condition is met Pandas:如果满足条件,则将列的值替换为前一行的值 - Pandas: Replace value of column with previous row value if condition is met 如何获取 pandas 列中的前一行值 - how can I get a previous row value in pandas column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM