我想将时间序列DataFrame的索引转换为日期时间。问题是有些索引是时间戳,有些是日期时间。
time C1
2020-10-18 13:38:43.349 0.046
2020-10-18 13:52:34.104 0.099
1602824859304 1.000
1602824934121 0.007
此:df['time'] = pd.to_datetime(df['time'], unit='ms')
收益率:ValueError: non convertible value time with the unit 'ms'
此:df["time"] = df["time"].apply(lambda x: pd.to_datetime(x,errors='ignore').strftime('%Y-%m-%d %H:%M') if len(x) !=0 else "----")
收益率:AttributeError: 'str' object has no attribute 'strftime'
这是一个类似的问题,但不适用于我的情况:
仅当字符串长度不为零时,才将数据帧列转换为日期时间
我期望的输出是所有的索引行都是日期时间格式。
让我们尝试识别所有作为时间戳的行,并分别转换它们:
mask = df['time'].str.contains(' ')
df['time'] = (pd.to_datetime(df.loc[mask,'time'])
.reindex(df.index)
.fillna(pd.to_datetime(df.loc[~mask, 'time'], unit='ms'))
)
输出:
time C1
0 2020-10-18 13:38:43.349 0.046
1 2020-10-18 13:52:34.104 0.099
2 2020-10-16 05:07:39.304 1.000
3 2020-10-16 05:08:54.121 0.007