user16304089
user16304089

Reputation:

Convert fractional values to decimal in Pandas

I have a dataframe with messy data.

df:
    1        2        3
--  -------  -------  -------
 0  123/100  221/100  103/50
 1  49/100   333/100  223/50
 2  153/100  81/50    229/100
 3  183/100  47/25    31/20
 4  2.23     3.2      3.04
 5  2.39     3.61     2.69

I want the fractional values to be converted to decimal with the conversion formula being

e.g:

The calculation is fractional value + 1

And of course leave the decimal values as is.

How can I do it in Pandas and Python?

Upvotes: 0

Views: 837

Answers (2)

Corralien
Corralien

Reputation: 120479

If you trust the data in your dataset, the simplest way is to use eval or better, suggested by @mozway, pd.eval:

>>> df.replace(r'(\d+)/(\d+)', r'1+\1/\2', regex=True).applymap(pd.eval)
      1     2     3
0  2.23  3.21  3.06
1  1.49  4.33  5.46
2  2.53  2.62  3.29
3  2.83  2.88  2.55
4  2.23  3.20  3.04
5  2.39  3.61  2.69

Upvotes: 1

belfner
belfner

Reputation: 232

A simple way to do this is to first define a conversion function that will be applied to each element in a column:

def convert(s):
    if '/' in s: # is a fraction
        num, den = s.split('/')
        return 1+(int(num)/int(den))
    else:
        return float(s)

Then use the .apply function to run all elements of a column through this function:

df['1'] = df['1'].apply(convert)

Result:

df['1']:

0    2.23
1    1.49
2    2.53
3    2.83
4    2.23
5    2.39

Then repeat on any other column as needed.

Upvotes: 1

Related Questions