如何使用 python 转换数据框中的 mm:ss 值

how to convert mm:ss values in dataframe using python

我是 pandas 的新手,有一个表格数据,其中有 3 列,其中(df.info() 给出 object 类型)值都在 sm:s。我想将所有 m:s 值转换为 s 值。我会留下一些例子来说明。

现在:

VT          FT          TTPF
1:28.8      1:17.2      30.4
1:06.4      1:06.2      16.8
38.6        26.2        10.8

应该是:

VT          FT          TTPF
88.8        77.2        30.4
66.4        66.2        16.8
38.6        26.2        10.8

很抱歉,如果我无法提供所有详细信息。随时请求编辑

首先 select 仅对具有 ::

的行按 DataFrame.select_dtypes and DataFrame.apply custom function with Series.str.contains for filter values with : and then Series.str.split with casting to floats, multiple by 60 and sum together in Series.mask 串列
def f(x):
    m = x.str.contains(':')
    y = x[m].str.split(':', expand=True)
    return x.mask(m, y[0].astype(float) * 60 + y[1].astype(float))

c = df.select_dtypes(object).columns
df[c] = df[c].apply(f).astype(float)
print (df)
     VT    FT  TTPF
0  88.8  77.2  30.4
1  66.4  66.2  16.8
2  38.6  26.2  10.8

另一个想法是使用 DataFrame.applymap 进行元素处理:

def f(x):
    if ':' in str(x):
        a, b = x.split(':')
        return float(a) * 60 + float(b)
    else:
        return float(x)

df = df.applymap(f)
print (df)
     VT    FT  TTPF
0  88.8  77.2  30.4
1  66.4  66.2  16.8
2  38.6  26.2  10.8