在序列中使用映射时,如何指示数据类型



我在Pandas系列中使用map来应用一个函数,该函数提取表示日期的任何字符串,如果该字符串中没有日期,则提取空字符串。

import pandas as pd
import dateparser
text_series = pd.Series(data={'label 1':'some text',
'label 2':'something happened on 2012-12-31',
'label 3':'2013-12-31'})
new_series = text_series.map(lambda x: dateparser.search.search_dates(x)[-1][1] if dateparser.search.search_dates(x) else "")

代码按预期工作,我以一个新的系列结束,该系列包含表示字符串中日期的datetime对象。

label 1          NaT
label 2   2012-12-31
label 3   2013-12-31
dtype: datetime64[ns]

我的问题是,我收到了一个警告,因为map从函数返回的字符串中推断出日期时间,而且显然这种行为是不赞成的,应该明确指示类型。

FutureWarning: Inferring datetime64[ns] from data containing strings is deprecated and will be removed in a future version. To retain the old behavior explicitly pass Series(data, dtype={value.dtype})

当旧行为停止工作时,我如何避免此警告并避免此代码停止工作?

使用regex 采取了不同的方法

import pandas as pd
import regex as re
text_series = pd.Series(data={'label 1':'some text',
'label 2':'something happened on 2012-12-31',
'label 3':'2013-12-31'})
def make_dt(row):
x = re.search(r'(d{4}-d{2}-d{2})', row)
if x:
return pd.to_datetime(x.group(1))
new_series = text_series.apply(make_dt)

如果长度不匹配:r'(d-d-d)'

output:
label 1          NaT
label 2   2012-12-31
label 3   2013-12-31
dtype: datetime64[ns]

最新更新