我想将df‘column’列中的值转换为字符串obj到timedelta64。
已试用this....> df2 2‘芯片时间’=pd.to_timedelta(df2 2‘芯片时间’)
但是获取错误消息...> ValueError:预期的hh:mm:ss格式
发布于 2022-09-29 06:42:37
可以对str.replace使用regex对匹配'x:x'的值添加'0:':
df2['Chip Time'] = pd.to_timedelta(df2['Chip Time']
.str.replace('^(\d+:\d+)$', r'0:\1', regex=True)
)示例输出:
Chip Time
0 0 days 00:16:48
1 0 days 01:07:51已使用的投入:
Chip Time
0 16:48
1 1:07:51发布于 2022-09-29 06:01:38
如果string只有一个: by Series.str.count和Series.mask,则可以添加Series.mask。
df2 = pd.DataFrame({"Chip Time": ['10:04','1:45:23','23:12']})
s = df2['Chip Time'].mask(df2['Chip Time'].str.count(':').eq(1), '00:' + df2['Chip Time'])
#alternative:
s = np.where(df2['Chip Time'].str.count(':').eq(1), '00:', '') + df2['Chip Time']
print (s)
0 00:10:04
1 1:45:23
2 00:23:12
Name: Chip Time, dtype: object
df2['Chip Time'] = pd.to_timedelta(s)
print (df2)
Chip Time
0 0 days 00:10:04
1 0 days 01:45:23
2 0 days 00:23:12https://stackoverflow.com/questions/73890892
复制相似问题