Python converting a column in df of strings in format "%M:%S.%f" into float of number of seconds

huangapple go评论62阅读模式
英文:

Python converting a column in df of strings in format "%M:%S.%f" into float of number of seconds

问题

将D Interval列中的字符串格式 %M:%S.%f 转换为秒的浮点数。

英文:

I know this is a simple fix, I just cannot get it to work for the entire column. All I want to do is convert the strings in D Interval of this format %M:%S.%f to a float number of seconds.

Python converting a column in df of strings in format "%M:%S.%f" into float of number of seconds

答案1

得分: 2

你可以尝试这个:

df["D Interval"] = pd.to_timedelta(df["D Interval"].radd("00:")).dt.total_seconds()

输出:

print(df)

   Index   D Time  D Interval
0      1  00:54.3       54.30
1      2  00:57.1        2.80

使用的输入:

df = pd.DataFrame(
    {"Index": [1, 2],
     "D Time": ["00:54.3", "00:57.1"],
     "D Interval": ["00:54.3", "00:02.8"]}
)
英文:

You can try this :

df["D Interval"] = pd.to_timedelta(df["D Interval"].radd("00:")).dt.total_seconds()

​Output :

print(df)
​
   Index   D Time  D Interval
0      1  00:54.3       54.30
1      2  00:57.1        2.80

Input used :

df = pd.DataFrame(
    {"Index": [1, 2],
     "D Time": ["00:54.3", "00:57.1"],
     "D Interval": ["00:54.3", "00:02.8"]}
)

答案2

得分: 1

你可以使用 str.extract

df['D Interval'] = (df['D Interval'].str.extract(r'(\d+):(\d+)\.(\d+)')
                                    .astype(int).mul([60, 1, 0.1]).sum(axis=1))
print(df)

# 输出结果
    D Time  D Interval
0  00:54.3        54.3
1  00:57.1         2.8

也可以使用 str.split

df['D Interval'] = (df['D Interval'].str.split('[:.]', expand=True)
                                    .astype(int).mul([60, 1, 0.1]).sum(axis=1))
英文:

You can use str.extract:

df['D Interval'] = (df['D Interval'].str.extract(r'(\d+):(\d+)\.(\d+)')
                                    .astype(int).mul([60, 1, 0.1]).sum(axis=1))
print(df)

# Output
    D Time  D Interval
0  00:54.3        54.3
1  00:57.1         2.8

It works with str.split too:

df['D Interval'] = (df['D Interval'].str.split('[:.]', expand=True)
                                    .astype(int).mul([60, 1, 0.1]).sum(axis=1))

huangapple
  • 本文由 发表于 2023年5月11日 05:47:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76222769.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定