我是 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)
我有這個錯誤資訊:
型別錯誤:“時間戳”和“str”的實體之間不支持“<”
我理解錯誤,但我不知道如何解決
uj5u.com熱心網友回復:
from datetime import datetime
datetime.strptime("2020-01-01","%Y-%m-%d")
這是將字串轉換為日期時間物件的方法
uj5u.com熱心網友回復:
看來您只需要將condition函式應用于一列,因此您可以使用以下方法修復它pd.to_datetime:
def condition(row):
if row < pd.Timestamp('2020-01-01'):
return "<2020"
if "2020" in row:
return "2020"
if (row >= pd.Timestamp("2021-01-01")) & (row <=pd.Timestamp("2021-06-30")):
return "S1 2021"
if (row > pd.Timestamp("2021-06-30")) & (row <=pd.Timestamp("2021-12-31")):
return "S2 2021"
df1['Année'] = df1['Item - Accounting Date'].apply(condition)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/390625.html
