【发布时间】:2022-01-23 18:54:55
【问题描述】:
我是 python 新手,我想添加一个基于具有多个条件的日期的列。 我的数据来自工作表。
目前我的代码如下所示:
#Save data in a DataFrame
df1 = pd.read_excel(stream_io1, sheet_name = "Sheet1", header=0)
# Use Accounting Date
df1['Item - Accounting Date'] = pd.to_datetime(df1['Item - Accounting Date'], format='%Y-%m-%d')
def condition(row):
if (row['Item - Accounting Date'] < '2020-01-01') in row['Item - Accounting Date']:
return "<2020"
if "2020" in row['Item - Accounting Date']:
return "2020"
if (row[(row['Item - Accounting Date'] >= "01/01/2021") & (row['Item - Accounting Date'] <="30/06/2021")]) in row['Item - Accounting Date']:
return "S1 2021"
if (row[(row['Item - Accounting Date'] > "30/06/2021") & (row['Item - Accounting Date'] <="31/12/2021")]) in row['Item - Accounting Date']:
return "S2 2021"
df1['Année'] = df1.apply(condition, axis = 1)
我有这个错误信息:
TypeError:“Timestamp”和“str”实例之间不支持“
我了解错误,但我不知道如何解决它
【问题讨论】:
-
在比较中使用类似
"2021-06-30"的格式始终而不是"30/06/2021"。
标签: python pandas dataframe datetime