如何将英尺和英寸的分数格式转换为小数?

时间:2019-05-06 02:08:38

标签: python string pandas numpy fractions

我正在使用通过熊猫导入的数据框。我有一列包含以英尺和英寸为单位的长度值,格式为小数。

我想进行以下转换:

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

我想我将不得不尝试分解字符串的每一段并将其转换为十进制,然后将它们全部加在一起。我一直在使用Excel来执行此任务,因此我不确定如何在Python中处理它。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

您可以使用正则表达式,命名组为@KlausD。建议这样:

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

输出:

          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