如何检查date1是否小于date2,并在dataframe的新列中赋值

2024-05-14 19:54:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我想比较数据框中的两个日期(装运日期和理论装运日期),如果装运日期在理论装运日期之前/之上,则分配值“1”,如果装运日期在理论装运日期之后,则分配值“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


Tags: dfdateobjecttimedt理论装运creation
3条回答

这样做很容易。请确保日期已正确转换为日期时间

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,则使用轴=1来考虑轴1中的数据文件。

df['on time'] = df.apply(lambda x: int(x['Shipment Dt']<=x['theoretical ship date']),axis=1)

创建一个布尔掩码,并将其转换为int,以获得一列1和0,具体取决于您的条件是否满足:

df['on time'] = (df['Shipment Dt'] <= df['theoretical ship date']).astype(int)

多亏了@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)

相关问题 更多 >

    热门问题