Pandas,如果列的值小于该变量,则用变量(负)替换该列的值,否则保持值不变

Pandas, Replace values of a column with a variable (negative) if it is less than that variable, else keep the values as is

说:

m = 170000 , v = -(m/100)

{'01-09-2021': 631, '02-09-2021': -442, '08-09-2021': 6, '09-09-2021': 1528, '13-09-2021': 2042, '14-09-2021': 1098, '15-09-2021': -2092, '16-09-2021': -6718, '20-09-2021': -595, '22-09-2021': 268, '23-09-2021': -2464, '28-09-2021': 611, '29-09-2021': -1700, '30-09-2021': 4392}

如果值小于 v,我想用 v 替换 'Final' 列中的值,否则保留原始值。尝试了 numpy.where 、 df.loc 等但没有用。

你可以使用 clip:

df['Final'] = df['Final'].clip(-1700)
print(df)

# Output:
          Date  Final
0   01-09-2021    631
1   02-09-2021   -442
2   08-09-2021      6
3   09-09-2021   1528
4   13-09-2021   2042
5   14-09-2021   1098
6   15-09-2021  -1700
7   16-09-2021  -1700
8   20-09-2021   -595
9   22-09-2021    268
10  23-09-2021  -1700
11  28-09-2021    611
12  29-09-2021  -1700
13  30-09-2021   4392

或者经典np.where:

df['Final'] = np.where(df['Final'] < -1700, -1700, df['Final'])

设置:

df = pd.DataFrame({'Date': d.keys(), 'Final': d.values()})

你可以试试:

df.loc[df['Final']<v, 'Final'] = v

输出:

          Date  Final
0   01-09-2021    631
1   02-09-2021   -442
2   08-09-2021      6
3   09-09-2021   1528
4   13-09-2021   2042
5   14-09-2021   1098
6   15-09-2021  -1700
7   16-09-2021  -1700
8   20-09-2021   -595
9   22-09-2021    268
10  23-09-2021  -1700
11  28-09-2021    611
12  29-09-2021  -1700
13  30-09-2021   4392