如果列之间存在任何 NaN 值,如何处理脚本在 python 中 [英] How to process the script in case of any NaN values between the column In python
本文介绍了如果列之间存在任何 NaN 值,如何处理脚本在 python 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试处理我正在尝试查找列之间的月份的脚本,该脚本工作正常,但只要任何字段为空,就会出现错误.
I am trying to process the an script Where i am Trying to find the Months between the column , The script is working fine but whenever any field is blank it Gives an error.
如果中间有任何 NaN 值,它必须跳过并移动到下一行.
If any NaN values comes in between It must skips and move to Next rows.
如何解决错误:
输入数据:
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:start
和 end
都不能是 NaT
Error: ValueError: Neither start
nor end
can be NaT
推荐答案
IIUC,你的函数需要一个 if else 块:
IIUC, your function needs a if else block:
def get_date_list(x):
if not pd.isna(x['Month1']):
return ",".join(
item.strftime("%b %Y")
for item in pd.date_range(x['Month1'], x['Month2'], freq="MS")
)
return np.nan
df['Month_list'] = df.apply(lambda x: get_date_list(x), axis=1)
print(df)
Month1 Month2 Month_list
0 Mar2020 Dec2020 Mar 2020,Apr 2020,May 2020,Jun 2020,Jul 2020,A...
1 Nov2020 Jan2021 Nov 2020,Dec 2020,Jan 2021
2 NaN NaN NaN
3 Sep2020 Feb2021 Sep 2020,Oct 2020,Nov 2020,Dec 2020,Jan 2021,F...
4 Oct2020 Dec2020 Oct 2020,Nov 2020,Dec 2020
5 NaN NaN NaN
6 Dec2020 Mar2021 Dec 2020,Jan 2021,Feb 2021,Mar 2021
这篇关于如果列之间存在任何 NaN 值,如何处理脚本在 python 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文