Home > front end >  dynamically replace a value within a range, and change the next closest value
dynamically replace a value within a range, and change the next closest value

Time:09-28

I am looking for an elegant way to select columns that contain a value under 15, and if they do, i want to change it to 1. I also want to change the next closest number to 2. any suggestions would be great. I can subset accordingly but am stuck with dynamically adapting the next closest number

df i have

df = pd.DataFrame(data={'a':[1,1,13,23,40],
                        'b': [89.87,1,12,4,8],
                        'c': [45,12,901,12,29]}).astype(float)

df i want

expected = pd.DataFrame(data={'a':[1,1,1,2,40],
                        'b': [2,1,1,1,1],
                        'c': [45,1,901,1,2]}).astype(float)

CodePudding user response:

You can use masks and mask:

mask = df.lt(15)                    # values lower than 15
mask2 = df.eq(df.mask(mask).min())  # min values, excluding values below 15

df.mask(mask, 1).mask(mask2, 2)     # replacing mask with 1, mask2 with 2

output:

      a    b      c
0   1.0  2.0   45.0
1   1.0  1.0    1.0
2   1.0  1.0  901.0
3   2.0  1.0    1.0
4  40.0  1.0    2.0
  • Related