如何在pandas dataframe中提取仅包含纪元细节,而将其他内容排除在外?

2024-04-24 16:46:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个时间的数据集。我需要提取epochtime并将其转换为normalDD-MM-YYYY格式以及HH:MM格式中的时间细节。 这个列就像本文件:你知道吗

Index       Date                                                                  
0        {'$date': {'$numberLong': '1562005805010'}}   

我尝试过使用regex、extract和replace方法,但它们将date列转换为NaN

df1['date'] = df1['date'].str.extract('(\d+)', expand=False)

我只希望显示epoch,以便将它们转换为日期和时间。 Here is the column that I have


Tags: 文件数据dateindex格式hh时间extract
1条回答
网友
1楼 · 发布于 2024-04-24 16:46:00

如果值是字符串,则首先通过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'])

如果值为嵌套dict,则仅按键选择:

print (type(df['Date'].iat[0]))
<class 'dict'>

s = df['Date'].apply(lambda x: x['$date']['$numberLong'])

最后使用^{}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

相关问题 更多 >