0

I want to replace each range in the dataset to a certain value for ex:
0 - 0.3333 replace it to 1
0.33334 - 0.6666 replace it to 2
0.66667 - 0.9999 replace it to 3

code (didnt work):
a = 0 < df < 0.3333 b = 0.3334 < df < 0.666 c = 0.6667 < df < 0.9999 df df.replace(a,1) df = df.replace(b,2) df = df.replace(c,3)

I did it for one column and it worked, but I want to do it for the whole data set at once:

`df.loc[df["POS_D1"] < 0.3333, "POS_D1"] = 1   df.loc[df["POS_D1"] < 0.6666, "POS_D1"] = 2   

df.loc[df["POS_D1"] < 0.9999, "POS_D1"] = 3`

1 Answers1

0

This should be pretty simple and quick:

df.applymap(lambda x: math.ceil(x/0.3333))

Ex:

>>> df
          A         B         C         D
0  0.333300  0.251188  0.179800  0.429367
1  0.698581  0.906103  0.775302  0.536394
2  0.750087  0.409743  0.739812  0.500135
3  0.031756  0.532655  0.324095  0.821554
4  0.857215  0.452921  0.981266  0.093581
5  0.328374  0.587001  0.528952  0.077552
6  0.056384  0.478333  0.942758  0.937025
7  0.799077  0.367845  0.828240  0.202491
8  0.169304  0.471145  0.453163  0.364927
9  0.572563  0.683666  0.004306  0.796554
>>> df.applymap(lambda x: math.ceil(x/0.3333))
   A  B  C  D
0  1  1  1  2
1  3  3  3  2
2  3  2  3  2
3  1  2  1  3
4  3  2  3  1
5  1  2  2  1
6  1  2  3  3
7  3  2  3  1
8  1  2  2  2
9  2  3  1  3

Edit:

To apply to all but the first 3 columns:

df.iloc[:,3:]=df.iloc[:,3:].applymap(lambda x: math.ceil(x/0.3333))
>>> df
          A         B         C    D
0  0.081549  0.251188  0.179800  2.0
1  0.698581  0.906103  0.775302  2.0
2  0.750087  0.409743  0.739812  2.0
3  0.031756  0.532655  0.324095  3.0
4  0.857215  0.452921  0.981266  1.0
5  0.328374  0.587001  0.528952  1.0
6  0.056384  0.478333  0.942758  3.0
7  0.799077  0.367845  0.828240  1.0
8  0.169304  0.471145  0.453163  2.0
9  0.572563  0.683666  0.004306  3.0
Boskosnitch
  • 774
  • 3
  • 8