Python 与外部列表中的元素相比,如何仅更改熊猫的系列值?

Python 与外部列表中的元素相比,如何仅更改熊猫的系列值?,python,python-3.x,pandas,calculated-columns,Python,Python 3.x,Pandas,Calculated Columns,我有一个要保留在列名中的引用词列表,如果值不属于列表中排除的元素,则用其他替换该值。以下是我的想法: list_excluded = ['egWord1', 'egWord2'] df['new'] = df['old'] # I only want to change values in 'new' column to 'other' if the value is not 'egWord1' or 'egWord2' df.loc[df['new'] == 'other', df['co

我有一个要保留在列名中的引用词列表,如果值不属于列表中排除的元素,则用其他替换该值。以下是我的想法:

list_excluded = ['egWord1', 'egWord2']

df['new'] = df['old']

# I only want to change values in 'new' column to 'other' if the value is not 'egWord1' or 'egWord2'
df.loc[df['new'] == 'other', df['columnName']] = list_excluded
您可以使用“申请”进行类似操作:

代码:

测试代码:

结果:

您可以使用“申请”进行类似操作:

代码:

测试代码:

结果:


在没有任何样本数据或所需输出的情况下很难做到这一点,但听起来好像您正在尝试选择列表中不存在的值,然后将df['new']设置为'other'。对吗?如果是,请尝试以下方法:

df.loc[~df['columnName'].isin(list_excluded), df['new']] = 'other'

这是假设您已经完成了查找,而另一个答案中包含了两个步骤

在没有任何样本数据或所需输出的情况下很难做到这一点,但听起来好像您试图选择列表中不存在的值,然后将df['new']设置为'other'。对吗?如果是,请尝试以下方法:

df.loc[~df['columnName'].isin(list_excluded), df['new']] = 'other'

这是假设您已经完成了查找,而另一个答案中包含了两个步骤

稍微快一点的解决方案:

df['new'] = np.where(~df.old.isin(list_excluded), 'other', df.old)

稍微快一点的解决方案:

df['new'] = np.where(~df.old.isin(list_excluded), 'other', df.old)

我不使用in,而是使用not,这是我的意图。谢谢。我用的不是in,而是not,这是我的意图。谢谢
df['new'] = np.where(~df.old.isin(list_excluded), 'other', df.old)