结合pandas使用:np.where可以方便地在pandas数据框中进行条件判断和值的赋值操作,根据不同的条件生成新的列值或修改现有列的值。
np.where函数在数据分析和处理中非常有用,可以快速地根据条件进行数据的筛选和转换。
需求:test数据框中的广告来源和媒介两列的值来生成新的列来源媒介。如果广告来源为NaN,则新列也为NaN;如果媒介为NaN,新列的值为广告来源加上/;如果两列都有值,新列的值为广告来源加上/再加上媒介
# 方法1:
test['来源媒介'] = np.where(pd.isna(test['广告来源']), np.nan,
np.where(pd.isna(test['媒介']), test['广告来源'] + r' / ',
test['广告来源'] + r' / ' + test['媒介']))
# 方法2: 将缺失值 NAN,都转成 'nan'
test['来源媒介'] = test['广告来源'].astype(str) + r' / ' + test['媒介'].astype(str)
如果两者都为NAN,则 'nan/nan'