如果值 = NaN 那么

If value = NaN then

我是 Python 的新手,我正在尝试使用 Pandas(我可以使用 VBA,但需要很长时间)来合并 2 张 Excel 变成 1(就像 Excel 中的 Vlookup 函数)。我有如下问题:

这是我的代码:

import pandas as pd

df1 = pd.DataFrame({'v_contract_number': ['VN120001438','VN120001439'],'maturity date': ['31/12/2021','31/12/2021']})
df2 = pd.DataFrame({'v_contract_number': ['VN120001438','VN120001439'], 'd_revised_maturity_date': ['31/12/2021',' ']})
print(df1)

# df1
  v_contract_number maturity date
0       VN120001438    31/12/2021
1       VN120001439    31/12/2021

print(df2)

# df2
  v_contract_number d_revised_maturity_date
0       VN120001438              31/12/2021
1       VN120001439  

results = pd.merge(df1, df2, on=['v_contract_number'],how='left')
print(results)

# results
  v_contract_number maturity date d_revised_maturity_date
0       VN120001438    31/12/2021              31/12/2021
1       VN120001439    31/12/2021  

我想要的是如果 'd_revised_maturity_date' 为 null 那么 null = 'maturity date'

我的预期结果是:

  v_contract_number maturity date d_revised_maturity_date
0       VN120001438    31/12/2021              31/12/2021
1       VN120001439    31/12/2021              31/12/2021

我可以在 excel 中使用 iferror 完成这项任务,但我不知道如何在 python 中完成。

谢谢和最诚挚的问候

您可以使用 fillna 用另一列填充 na/nan 个值。

df['d_revised_maturity_date'].fillna(df['maturity date'], inplace=True)

合并后,可以使用mask:

d_date = results.d_revised_maturity_date
results.d_revised_maturity_date = d_date.mask(d_date.eq(" "), results["maturity date"])

这将用 maturity date

的相应值填充 d_revised_maturity_date 的空位(通过 eq" " 找到)

得到

>>> results

  v_contract_number maturity date d_revised_maturity_date
0       VN120001438    31/12/2021              31/12/2021
1       VN120001439    31/12/2021              31/12/2021

(如果您要替换 d_revised_maturity_date 列中的任何类型的空格,您可以将上面的 d_date.eq(" ") 更改为

d_date.str.fullmatch(r"\s*")

其中包括完全空的字符串,一个或多个空格。)

np.where() 的组合可以发挥您的优势。

np.where(pd.isna(df["d_revised_maturity_date"]), df["maturity date"], df["d_revised_maturity_date"])

结果['d_revised_maturity_date'] = 结果['maturity date'].apply(lambda x: x if x == None else x)

df['d_revised_maturity_date'].fillna(df['maturity date'], inplace=True)

应该适合你