首页 > 解决方案 > 将 if then 与 python pandas 一起使用

问题描述

我有一个在 python 中使用 pandas 的数据集,并且想对特定列应用 if-then-else 规则。

如果存在缺失值,则将其替换为从同一观察中的另一列中获取的特定值,否则什么也不做。

我的数据集由以下代码生成:

results = df2.merge(df1,on="sku", how="left")

需要填充的列变量,如果为空是“stock_y”。如果为空,则应将列变量“stock_x”的值复制到“stock_y”。在 stock_y 已经被填满的情况下,代码应该跳过观察。

标签: pythonpandasvlookup

解决方案


签出Series.combine_first

results['stock_y'] = results['stock_y'].combine_first(results['stock_x'])

推荐阅读