Python 替换列表中的值

Python 替换列表中的值,python,pandas,Python,Pandas,我有一个数据框,其中列是一个列表。我试图使用替换列表中的值,但没有成功。我试图用任何值替换字符串other df=pd.DataFrame({'sales_niche':[['B2B','Services','Services','Other','Other']}) df['sales_niche'].替换('Other','Any value') df['sales_niche'].替换({'Other':'Any value'}) 输出 0 [B2B, Services, S

我有一个数据框,其中列是一个列表。我试图使用替换列表中的值,但没有成功。我试图用任何值替换字符串other

df=pd.DataFrame({'sales_niche':[['B2B','Services','Services','Other','Other']})
df['sales_niche'].替换('Other','Any value')
df['sales_niche'].替换({'Other':'Any value'})
输出

0        [B2B, Services, Services, Other, Other]
知道我做错了什么吗?当处理非列表的列时,它可以正常工作。感谢您的帮助


谢谢

使用此数据帧作为示例

df = pd.DataFrame({'sales_niche' : [['B2B', 'Services', 'Services', 'Other', 'Other']]})
运行此代码

repl = { 'Other': 'Any value' }
df['sales_niche'] = df['sales_niche'].apply(lambda l:[repl.get(e,e) for e in l])
df
给你这个


sales_niche
0   [B2B, Services, Services, Any value, Any value]

replace
仅适用于精确的值,或在
regex=True
时使用子字符串。在您的例子中,您有一个字符串列表,因此
replace
不是一个好的选择

通常,应避免在数据框内列出。如果必须使用它,可以循环:

df = pd.DataFrame({'sales_niche':[['B2B', 'Services', 'Services', 'Other', 'Other']]})

d = { 'Other': 'Any value' }

df['sales_niche'].apply(lambda x: [d[a] if a in d else a for a in x])
输出:

0    [B2B, Services, Services, Any value, Any value]
Name: sales_niche, dtype: object
您还可以分解数据并使用
替换
,然后重新聚合:

df['sales_niche'].explode().replace(d).groupby(level=0).agg(list)

但是开销可能使这种方法没有上面简单的应用那么有用。

制作一个小示例数据帧并用代码向我们展示您正在做的事情应该很容易。就这么做了,谢谢。