[英]Changing column based on multiple conditions and previous rows values pandas
I have this dataframe.我有这个数据框。 I need to replace NaNs in column rank to a value based on multiple conditions.
我需要将列排名中的 NaN 替换为基于多个条件的值。 If column min is higher than 3 previous rows of max column then rank equals to min .
如果列min高于max列的前 3 行,则rank等于min 。 Otherwise, I need to copy the previous value of rank
否则,我需要复制rank的先前值
max min rank
0 128.20 117.87 117.87
1 132.72 122.29 122.29
2 138.07 124.89 124.89
3 137.02 128.46 NaN
4 130.91 129.86 NaN
5 200.15 190.54 NaN
6 199.18 191.79 NaN
7 210.44 201.94 NaN
The desired result is想要的结果是
max min rank
0 128.20 117.87 117.87
1 132.72 122.29 122.29
2 138.07 124.89 124.89
3 137.02 128.46 124.89
4 130.91 129.86 124.89
5 200.15 190.54 190.54
6 199.18 191.79 190.54
7 210.44 201.94 201.94
IIUC, here's one way: IIUC,这是一种方法:
df['rank'].mask(pd.concat([df['min'].shift(i) for i in range(3)], 1).apply(
lambda x: x < df['min']).all(1), df['min']).ffill()
max min rank
0 128.20 117.87 117.87
1 132.72 122.29 122.29
2 138.07 124.89 124.89
3 137.02 128.46 124.89
4 130.91 129.86 124.89
5 200.15 190.54 190.54
6 199.18 191.79 190.54
7 210.44 201.94 201.94
You can try:你可以试试:
df["rank"].update(df[df["min"]>df["max"].rolling(3).max().shift(1)]["min"])
df["rank"].ffill(inplace=True)
>>> df
max min rank
0 128.20 117.87 117.87
1 132.72 122.29 122.29
2 138.07 124.89 124.89
3 137.02 128.46 124.89
4 130.91 129.86 124.89
5 200.15 190.54 190.54
6 199.18 191.79 190.54
7 210.44 201.94 201.94
The rolling
and shift
functions are being used to check if the current min
is greater than the max
of the three previous max
.的
rolling
和shift
功能被用来检查当前min
比大于max
的三个先前的max
。
The ffill
carries forward the previous value. ffill
继承了先前的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.