根据条件用 np.select 和 np.where 替换 df 中的值

replacing values in df based on condition with np.select and np.where

我有一个 data_terms 的列表,我想循环遍历 df 的列,以用单词“数据库”替换 data_terms 中与任何项目匹配的所有实例。我试过 np.select:

discrete_distributed_bar["profile_standardized"] = np.select(
    [discrete_distributed_bar["profile_standardized"].isin(data_terms)],
    ["database"],
    default=discrete_distributed_bar.profile_standardized,
)

和 np.where:

for index, row in discrete_distributed_bar["profile_standardized"].items():
    np.where(
        discrete_distributed_bar["profile_standardized"].isin(data_terms),
        "database",
        row,
    )

但替换实际上并没有发生。我在这里错过了什么?

感谢您的帮助!

这里的解决方案似乎应该简化:

discrete_distributed_bar["profile_standardized"] = discrete_distributed_bar["profile_standardized"].replace(data_terms, 'database')

但我认为数据存在一些问题(例如空格),请通过以下方式进行测试:

print (discrete_distributed_bar["profile_standardized"].isin(data_terms))

那么可以使用:

discrete_distributed_bar["profile_standardized"] = discrete_distributed_bar["profile_standardized"].str.strip().replace(data_terms, 'database')