【问题标题】:Pandas - Column Compare Return False when Nan's are present in both the columnsPandas - 当两列中都存在 Nan 时,列比较返回 False
【发布时间】:2019-06-21 06:22:51
【问题描述】:

我正在逐行比较两列。

当两列中都存在 NaN 时返回 false,如果存在 Nan,我想返回 True。

例如,

这是我正在使用的代码:-

Pre_Out_df[res_name] = Pre_Out_df[plain_col] == Pre_Out_df[b_col]

例如,当两个列都有 Nan 用于比较行时,这将返回 False。

【问题讨论】:

  • 用常数值填充nan,例如Pre_Out_df[plain_col].fillna(1) == Pre_Out_df[b_col].fillna(1)

标签: python pandas


【解决方案1】:

检查缺失或不缺失,然后检查DataFrame.all 以检查两个值是否为Trues 或 DataFrame.any 检查是否至少有一个值是True

df = pd.DataFrame({'plain_col':['1A12','1C12',np.nan],
                   'b_col':[np.nan,'1B',np.nan]})


df['res_name1'] = df[['plain_col', 'b_col']].isnull().all(axis=1)
df['res_name2'] = df[['plain_col', 'b_col']].isnull().any(axis=1)

df['res_name3'] = df[['plain_col', 'b_col']].notnull().all(axis=1)
df['res_name4'] = df[['plain_col', 'b_col']].notnull().any(axis=1)

print (df)
  plain_col b_col  res_name1  res_name2  res_name3  res_name4
0      1A12   NaN      False       True      False       True
1      1C12    1B      False      False       True       True
2       NaN   NaN       True       True      False      False

【讨论】:

  • 我想,我需要这样的东西 - Pre_Out_df[res_name] = Pre_Out_df[plain_col] == Pre_Out_df[b_col] || Pre_Out_df[[plain_col, b_col]].isnull().any(axis=1)
  • @Sid29 - 抱歉,需要Pre_Out_df[res_name] = (Pre_Out_df[plain_col] == Pre_Out_df[b_col]) | (Pre_Out_df[[plain_col, b_col]].isnull().any(axis=1)) 吗?
  • 小伙伴的建议 - 尝试在您的问题中添加一些示例数据和预期输出,以及您的代码,以及您尝试防止否决的内容。
  • 会的,先生。谢谢。
猜你喜欢
  • 1970-01-01
  • 2016-05-26
  • 2018-07-11
  • 1970-01-01
  • 2019-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
相关资源
最近更新 更多