我有一个包含 时间 的数据集。我需要提取纪元 time 并将其转换为正常的 DD MM YYYY 格式以及 HH: MM 格式的时间详细信息。 专栏是这样的:-
Index Date
0 {'$date': {'$numberLong': '1562005805010'}}
我尝试过使用正则表达式、提取和替换方法,但它们将日期列转换为 NaN
df1['date'] = df1['date'].str.extract('(\d+)', expand=False)
我只想显示纪元,以便将它们转换为日期和时间。 Here is the column that I have
最佳答案
如果值是字符串,首先通过 ast.literal_eval
将其转换为字典,然后选择:
print (type(df['Date'].iat[0]))
<class 'str'>
import ast
s = df['Date'].apply(lambda x: ast.literal_eval(x)['$date']['$numberLong'])
如果值是嵌套的字典,只能通过键选择:
print (type(df['Date'].iat[0]))
<class 'dict'>
s = df['Date'].apply(lambda x: x['$date']['$numberLong'])
最后一次使用 to_datetime
使用 unit
参数:
print (s)
0 1562005805010
Name: Date, dtype: object
df['Date'] = pd.to_datetime(s, unit='ms')
print (df)
Index Date
0 0 2019-07-01 18:30:05.010
关于python - 如何仅提取时代细节并将其他内容留在 pandas 数据框中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57052669/