Stephen
Stephen

Reputation: 121

How to convert feet and inches in fraction format to decimal?

I'm working with a dataframe that I've imported via pandas. I have a column that includes values of length that are in feet and inches formatted as a fraction.

I would like to do the following conversion:

Length           Length Decimal 
0'-10 11/64"     0.85
4'- 7 19/64"     4.61
0'- 3"           0.25
62'- 3 3/4"      62.31
58'- 5 43/64"    58.47
2'-11 13/16"     2.98

I imagine I would have to try to break out each segment of the string and convert them to decimal then add them all together. I have been using Excel for this task, so I'm unsure how to handle it in Python. Any help would be appreciated!

Upvotes: 3

Views: 2155

Answers (1)

Scott Boston
Scott Boston

Reputation: 153500

You can use regex, with named groups as @KlausD. suggest like this:

df = df.assign(**df['Length'].str.extract(r"(?P<Feet>\d+)'-\s?(?P<Inches>\d+)\s?(?P<Num>\d+)?\/?(?P<Dem>\d+)?\"")\
                        .astype(float).fillna(0))
df['Length Decimal'] = df.eval("Feet + Inches / 12") + np.where(df.Num == 0,0,(df["Num"]/df["Dem"])/12)
df

Output:

          Length  Length Decimal   Dem  Feet  Inches   Num
0   0'-10 11/64"        0.847656  64.0   0.0    10.0  11.0
1   4'- 7 19/64"        4.608073  64.0   4.0     7.0  19.0
2         0'- 3"        0.250000   0.0   0.0     3.0   0.0
3    62'- 3 3/4"       62.312500   4.0  62.0     3.0   3.0
4  58'- 5 43/64"       58.472656  64.0  58.0     5.0  43.0
5   2'-11 13/16"        2.984375  16.0   2.0    11.0  13.0

Upvotes: 3

Related Questions