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

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

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

我想进行以下转换:

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 中处理它。如有任何帮助,我们将不胜感激!

您可以使用正则表达式,命名组为@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