英文:
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.
答案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))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。



评论