[英]how to check if date1 is smaller date2 and assign value in new column in pandas dataframe
我想比較 dataframe 中的 2 個日期(裝運 Dt 和理論裝運日期),如果裝運日期早於/在理論裝運日期之前分配值“1”,如果裝運 Dt 日期在理論裝運日期之后分配值“0”。 我想將新值存儲在名為“准時”的列中
'''
Shipment Dt Creation date Lead time theoretical ship date
0 2020-01-02 2019-12-31 20 2020-01-28
1 2020-02-03 2019-12-27 30 2020-02-07
2 2020-04-03 2020-04-01 20 2020-04-29
3 2020-04-06 2020-04-01 30 2020-05-13
4 2020-04-07 2020-04-01 20 2020-04-29
dataTypeSeries = df.dtypes
print(dataTypeSeries)
Shipment Dt datetime64[ns]
Creation date datetime64[ns]
Lead time int64
theoretical ship date datetime64[ns]
dtype: object
''' 我試過了
df['on time'] = df['theoretical ship date'].apply(lambda x: '1' if x <= x['Shipment Dt'] else '0')
但我收到錯誤'Timestamp' object is not subscriptable
第二個問題是是否有辦法在不添加理論發貨日期列的情況下做到這一點--->如果發貨日期小於或等於創建日期加上交貨時間(以天為單位),則分配 1 否則為 0。
創建一個 boolean 掩碼並將其轉換為int
以獲取一列一和零,具體取決於您的條件是否滿足:
df['on time'] = (df['Shipment Dt'] <= df['theoretical ship date']).astype(int)
你可以很容易地做到這一點。確保日期正確轉換為日期時間
df["Shipment Dt"] = pd.to_datetime(df["Shipment Dt"])
df["theoretical ship date"] = pd.to_datetime(df["theoretical ship date"])
df['on time'] = (df['Shipment Dt'] <= df['theoretical ship date']).astype(int)
如果要使用 lambda,請使用 axis=1 來考慮軸 1 中的 dataframe。
df['on time'] = df.apply(lambda x: int(x['Shipment Dt']<=x['theoretical ship date']),axis=1)
感謝@Rajith Thennakoon 和@MrFuppes,我能夠在不添加“理論發貨日期”列的情況下將其編碼如下
temp = df['Lead time'].apply(np.ceil).apply(lambda x: pd.Timedelta(x, unit='D'))
df['on time'] = (df['Shipment Dt'] <= (df['Creation date']+temp)).astype(int)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.