I have this dataframe. I need to replace NaNs in column rank to a value based on multiple conditions. If column min is higher than 3 previous rows of max column then rank equals to min . Otherwise, I need to copy the previous value of 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:
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
.
The ffill
carries forward the previous value.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.