Pandas应用函数在Timestamp上返回None



在我的数据集中,我有一个熊猫时间戳的列,当我使用apply来执行一个条件熊猫返回None。在返回数据的函数(function name=get_start_times())中,我打印出成功打印数据及其类型的每一行,因此我知道数据在那里并且数据类型是有效的。我在下面添加了一个数据集的片段,下面是函数get_start_times代码。任何帮助都会很感激。输入图片描述

df["shift_start_time"] = df.apply(lambda x: get_start_times(x), axis=1)
def get_start_times(x: pd.Series):
if 0 <= x["site_time"].hour <= 6:
return x['shift_start_time'] - pd.Timedelta(days=1)
elif x["shift_start_time"].hour <= x["site_time"].hour <= 23:
return x["shift_start_time"]

首先我想做一个简单的更正。你可以这样做

def get_start_times(x: pd.Series):
if 0 <= x["site_time"].hour <= 6:
return x['shift_start_time'] - pd.Timedelta(days=1)
elif x["shift_start_time"].hour <= x["site_time"].hour <= 23:
return x["shift_start_time"]
df["shift_start_time"] = df.apply(get_start_time, axis=1)

关于这个问题,我看不到任何问题,但是你有ifelif,但是当我检查你的数据图片时,没有一个条件是真的,所以你的语句中没有满足任何条件,所以它什么也不返回。为了验证,你能在这里加上else语句吗?例如:

def get_start_times(x: pd.Series):
if 0 <= x["site_time"].hour <= 6:
return x['shift_start_time'] - pd.Timedelta(days=1)
elif x["shift_start_time"].hour <= x["site_time"].hour <= 23:
return x["shift_start_time"]
else:
# return anything that will tell you that this condition was met

希望这对你有帮助

最新更新