Home > Enterprise >  Pandas opposite strip function
Pandas opposite strip function

Time:05-10

I have a dataset with data which looks like this:

0         2
1         3
2       2 ½
3       3 ½
4       2 ½
       ... 
1532    1 ½
1533      1
1534    NaN
1535    NaN
1536    NaN

I am trying to convert all "1/2" fractions to a decimal number. 2 1/2 -> 2.5. I tried already plenty of different approaches. The last one was to strip the dataframe and replace the fraction with the decimal number.

0          [2]
1          [3]
2       [2, ½]
3       [3, ½]
4       [2, ½]
         ...  
1532    [1, ½]
1533       [1]
1534       NaN
1535       NaN
1536       NaN

However, I am not able to only change the fraction. It always changes the entire field. Which looks like this:

0       NaN
1       NaN
2        .5
3        .5
4        .5
       ... 
1532     .5
1533    NaN
1534    NaN
1535    NaN
1536    NaN

I used this code:

file2["room"] = file2["room"].str[1].replace("½", ".5")

So now I have two problems. The first, how do I replace only the decimal number and not the entire field and the second question is, how can I put them again together?

Maybe my approach is completely wrong. I would appreciate some other solutions.

CodePudding user response:

Try applying this on the first dataframe of your problem statement:

file2["room"] = file2["room"].str.replace(" ½", ".5")

Does it work for you?

CodePudding user response:

If there is a space before the ½ use

 file2["room"] = file2["room"].str.replace("½", "\s.5", regex=True)

otherwise use

file2["room"] = file2["room"].str.replace("½", ".5", regex=True)
  • Related