pandas panda python如何将持续时间转换为毫秒?

rjee0c15  于 2022-12-25  发布在  Python
关注(0)|答案(2)|浏览(185)

我有一个df,你可以通过复制并运行下面的代码:

import pandas as pd
from io import StringIO

df = """
 b_id          duration1                  duration2                          user

 384           28 days 21:05:16.141263     0 days 00:00:44.999706            Test
 
"""
df= pd.read_csv(StringIO(df.strip()), sep='\s\s+', engine='python')
df

我的问题是,如何将持续时间从"28天21:05:16.141263"转换为毫秒?

hxzsmxv2

hxzsmxv21#

首先将持续时间1转换为timedelta,然后再转换为毫秒

df['duration1'] = pd.to_timedelta(df['duration1'])
df['dur1_milli'] = df['duration1'].astype(np.int64) / int(1e6)
print(df)

产出数量

b_id               duration1               duration2  user    dur1_milli
0   384 28 days 21:05:16.141263  0 days 00:00:44.999706  Test  2.495116e+09

如果你想把它们展开
将其添加到代码的第一行

pd.set_option('display.float_format', lambda x: '%.3f' % x)

输出编号

b_id               duration1               duration2  user     dur1_milli
0   384 28 days 21:05:16.141263  0 days 00:00:44.999706  Test 2495116141.263
wydwbb8l

wydwbb8l2#

试试这个

df['duration1'].map(lambda x: pd.to_timedelta(x).total_seconds() * 1e3)

相关问题