问题
Consider the following table '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
I would like to convert the column date that is currently a string to a date by using apply() and datetime.strptime().
I tried the following:
format_date = "%Y-%m-%d"
df["date_new"] = df.loc[:,"date"].apply(datetime.strptime,df.loc[:,"date"],format_date)
I have the following error.
The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
I tried with different syntaxes (with args and **kwds arguments of apply() but I am always getting an error)
such as:
apply() takes exactly 2 arguments (3 given)
Can someone help me with the syntax ? Thank you.
回答1:
You should use pd.to_datetime():
df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d')
回答2:
You can do this:
df['date_new'] = df['date'].map(lambda date_string: datetime.strptime(date_string, format_string))
Since you are only operating on, and require data from a single column, you should use .map instead of .apply which will give you the entire row/column at once.
If you must use apply:
df['date_new'] = df.apply(lambda row: datetime.strptime(row['date'], format_string), axis=1)
The key here is axis=1, so you go row-wise
来源:https://stackoverflow.com/questions/52633719/syntax-to-use-df-apply-with-datetime-strptime