[英]How can I get a previous row from where the conditions are met in data frame in Pandas
I have very similar question to the one on this link , with only difference being to have multiple conditions met.我与此链接上的问题非常相似,唯一的区别是满足多个条件。
Let us assume that we have (sorted) dataframe, similar to the one in the example, with extra column:让我们假设我们有(排序的)数据框,类似于示例中的数据框,带有额外的列:
TIME VALUE EXTRA_FILTER
0 23:01 0 A
1 23:02 0 A
2 23:03 1 A
3 23:04 0 B
4 23:05 0 B
5 23:06 1 B
6 23:07 0 A
7 23:08 0 A
8 23:09 0 A
9 23:10 0 A
10 23:11 1 A
11 23:12 0 A
12 23:13 0 A
13 23:14 0 A
14 23:15 0 A
15 23:16 1 A
And I would like to have extra column called PREV_TIME next to each of the rows, which will contain the previous value of TIME column where both conditions to have the column VALUE equals to 1, and column EXTRA_FILTER equals to A are met, something like this:我想在每一行旁边都有一个名为 PREV_TIME 的额外列,它将包含 TIME 列的前一个值,其中满足列 VALUE 等于 1 和列 EXTRA_FILTER 等于 A 的两个条件,类似这样:
TIME VALUE EXTRA_FILTER PREV_TIME
0 23:01 0 A
1 23:02 0 A
2 23:03 1 A
3 23:04 0 B
4 23:05 0 B
5 23:06 1 B
6 23:07 0 A
7 23:08 0 A
8 23:09 0 A
9 23:10 0 A
10 23:11 1 A 23:03
11 23:12 0 A
12 23:13 0 A
13 23:14 0 A
14 23:15 0 A
15 23:16 1 A 23:11
IIUC, use pandas.Series.shift
: IIUC,使用
pandas.Series.shift
:
df["PREV_TIME"] = df[df["VALUE"].eq(1) & df["EXTRA_FILTER"].eq("A")]["TIME"].shift()
df["PREV_TIME"].fillna("", inplace=True)
print(df)
Output:输出:
TIME VALUE EXTRA_FILTER PREV_TIME
0 23:01 0 A
1 23:02 0 A
2 23:03 1 A
3 23:04 0 B
4 23:05 0 B
5 23:06 1 B
6 23:07 0 A
7 23:08 0 A
8 23:09 0 A
9 23:10 0 A
10 23:11 1 A 23:03
11 23:12 0 A
12 23:13 0 A
13 23:14 0 A
14 23:15 0 A
15 23:16 1 A 23:11
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.