如何仅提取时代细节并在 pandas 数据框中保留其他内容?

Posted

技术标签:

【中文标题】如何仅提取时代细节并在 pandas 数据框中保留其他内容?【英文标题】:How to extract only the epoch details and leave other things out in pandas dataframe? 【发布时间】:2019-11-24 22:03:40 【问题描述】:

我有一个包含 time 的数据集。我需要提取纪元 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

【问题讨论】:

【参考方案1】:

如果值是字符串,首先将其转换为 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'])

如果值是嵌套的dicts,只能按键选择:

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

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

最后使用to_datetimeunit 参数:

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

【讨论】:

当数据中只有 $numberLong 而没有 $date 时,此代码不起作用 @AbhasMehrotra - 然后将 x['$date']['$numberLong'] 更改为 x['$numberLong'] 我确实做到了,这是错误“TypeError: 'NoneType' object is not subscriptable”,我使用的代码是“df2['date'] = df2['date'].apply( lambda x:x['$numberLong'])"

以上是关于如何仅提取时代细节并在 pandas 数据框中保留其他内容?的主要内容,如果未能解决你的问题,请参考以下文章