将df.apply()与datetime.strptime

时间:2018-10-03 18:39:51

标签: python pandas datetime

请考虑下表“ df”:

    date        sales  
0   2021-04-10  483  
1   2022-02-03  226  
2   2021-09-23  374  
3   2021-10-17  186  
4   2021-07-17   35

我想通过使用apply()datetime.strptime()将当前为字符串的列日期转换为日期。

我尝试了以下操作:

format_date = "%Y-%m-%d"
df["date_new"] = df.loc[:,"date"].apply(datetime.strptime,df.loc[:,"date"],format_date)

我有以下错误。

  

系列的真值不明确。使用a.empty,a.bool(),   a.item(),a.any()或a.all()。

我尝试使用不同的语法(使用args的{​​{1}}和**kwds参数,但是我总是遇到错误) 例如:

  

apply()恰好接受2个参数(给定3个)

有人可以帮我语法吗?谢谢。

2 个答案:

答案 0 :(得分:0)

您应该使用pd.to_datetime()

df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d')

答案 1 :(得分:-1)

您可以这样做:

df['date_new'] = df['date'].map(lambda date_string: datetime.strptime(date_string, format_string))

由于您仅在进行操作,并且只需要来自一列的数据,因此应使用.map而不是.apply,这将一次为您提供整个行/列。

如果必须使用apply:

df['date_new'] = df.apply(lambda row: datetime.strptime(row['date'], format_string), axis=1)

这里的键是axis=1,所以您按行进行操作