如何仅提取纪元详细信息并在 pandas 数据框中留下其他内容?
How to extract only the epoch details and leave other things out in pandas dataframe?
我有一个时间为 的数据集。我需要提取纪元 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
将其转换为字典,然后 select:
print (type(df['Date'].iat[0]))
<class 'str'>
import ast
s = df['Date'].apply(lambda x: ast.literal_eval(x)['$date']['$numberLong'])
如果值只是嵌套的字典 select 按键:
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
我有一个时间为 的数据集。我需要提取纪元 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
将其转换为字典,然后 select:
print (type(df['Date'].iat[0]))
<class 'str'>
import ast
s = df['Date'].apply(lambda x: ast.literal_eval(x)['$date']['$numberLong'])
如果值只是嵌套的字典 select 按键:
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