[英]Assign value of existing column to new columns in pandas based on multiple conditions
[英]Python pandas and numpy: assign numerical values to new variable based on multiple conditions for existing variables
这在 Excel 中是微不足道的,为什么在 Python 中这么难?
目标是根据几个条件计算 state 变量,包括 state 变量的先前值。 值是已知的 integer,Min(3) 和 Max(3) 只是 3 个周期滚动 window 向前移动一个周期的最小值和最大值。 这就是我走多远。
Index Value Max(3) Min(3)
0 10 nan nan
1 20 nan nan
2 15 nan nan
3 25 20 10
4 15 25 15
5 10 25 15
6 15 20 10
根据以下条件计算 state 变量的最佳方法是什么:
在最终的 DataFrame 中应该如下所示:
Index Value Max(3) Min(3) State
0 10 nan nan nan
1 20 nan nan nan
2 15 nan nan nan
3 25 20 10 1
4 15 25 15 2
5 10 25 15 4
6 15 20 10 3
我主要使用 np.where() 函数尝试过这个,但是一旦我接近 c) 和 d) 条件,总是会遇到问题。
你可以使用这个:
df.loc[df.Value.gt(df['Max(3)']), 'State'] = 1
df.loc[df.Value.lt(df['Min(3)']), 'State'] = 4
df.loc[df.Value.between(df['Min(3)'], df['Max(3)']) & (df.State.shift(1).isin((3, 4))), 'State'] = 3
df.loc[df.Value.between(df['Min(3)'], df['Max(3)']) & (df.State.shift(1).isin((1,2))), 'State'] = 2
解释:
第一条语句检查 df.Value 大于 df['Max(3)'] 的位置并创建一个新列“State”,其中填充了 NaN,并且条件位置只有 1s
seconds 行设置 4s,其中 df.Value 小于 df.['Min(3)']
最后两个语句检查 df.Value 是否在 Max(3) 和 Min(3) 范围内,并比较 df.State 最后一个值 ( .shift )。 注意:如果数字是后续的,您也可以在此处使用.between代替.isin 。
np.select
可以很好地处理多种条件,具有良好的可读性
df['Value'] = df['Value'].astype(float)
conditions =
[
df['Value']>df['Max(3)'],
df['Value']<df['Min(3)'],
(df['Value']<=df['Max(3)']) & (df['Value']>= df['Min(3)']) & (df['State'].shift().isin((1,2))),
(df['Value']<=df['Max(3)']) & (df['Value']>= df['Min(3)']) & (df['State'].shift().isin((3,4)))
]
choicelist = [1, 4, 2, 3]
df['State'] = np.select(conditions, choicelist, np.nan)
print(df)
Index Value Max(3) Min(3) State
0 0 10.0 NaN NaN NaN
1 1 20.0 NaN NaN NaN
2 2 15.0 NaN NaN NaN
3 3 25.0 20.0 10.0 1.0
4 4 15.0 25.0 15.0 2.0
5 5 10.0 25.0 15.0 4.0
6 6 15.0 20.0 10.0 3.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.