Home > Enterprise >  Pandas, Replace values of a column with a variable (negative) if it is less than that variable, else
Pandas, Replace values of a column with a variable (negative) if it is less than that variable, else

Time:10-11

say:

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}

I want to replace values in column 'Final' with v if the value is less than v, else keep the original value. Tried numpy.where , df.loc etc but didn't work.

enter image description here

CodePudding user response:

Your can use 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

Or the classical np.where:

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

Setup:

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

CodePudding user response:

You can try:

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

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
  • Related