每当Month1&Month2列,脚本执行被卡住,其余数据没有得到处理。
脚本运行良好,但只要有任何行为空,就会出现错误。
需要建议如何处理具有NaN值的行。
输入数据:
Month1 Month2 Month_list
Mar2020 Dec2020
Nov2020 Jan2021
NaN NaN
Sep2020 Feb2021
Oct2020 Dec2020
NaN NaN
Dec2020 Mar2021
预期输出:
Month1 Month2 Month_list
Mar2020 Sep2020 Mar2020,Apr2020,May2020,Jun2020,Jul2020,Aug2020,Sep2020
Nov2020 Jan2021 Nov2020,Dec2020,Jan2021
NaN NaN NaN
Sep2020 Feb2021 Sep2020,Oct2020,Nov2020,Dec2020,Jan2021,Feb2021
Oct2020 Dec2020 Oct2020,Nov2020,Dec2020
NaN NaN NaN
Dec2020 Mar2021 Dec2020,Jan2021,Feb2021,Mar2021
我正在使用的脚本
def get_date_list(x):
return ",".join(
item.strftime("%b %Y")
for item in pd.date_range(x['Month1'], x['Month2'], freq="MS")
)
df['Month_list'] = df.apply(lambda x: get_date_list(x), axis=1)
使用上述代码时出现错误:ValueError:开始和结束都不能是NaT
您可以使用以下代码删除带有Nan值的行:
df= df.dropna()
df=df.reset_index(drop = True)