gpt4 book ai didi

python - 无法替换 pandas 列中包含 $ 的字符串

转载 作者:太空狗 更新时间:2023-10-30 00:22:39 24 4
gpt4 key购买 nike

我有一个dataframe

df = pd.DataFrame({'a':[1,2,3], 'b':[5, '12$sell', '1$sell']})

我想从 b 列替换 $sell

所以我尝试了如下所示的replace()方法

df['b'] = df['b'].str.replace("$sell","")

但它不会替换给定的字符串,它会给我与原始数据框相同的数据框。

当我将它与 apply 一起使用时,它正在工作

df['b'] = df['b'].apply(lambda x: str(x).replace("$sell",""))

所以我想知道为什么它在之前的案例中不起作用?

注意:我尝试只替换 $ 并且令人震惊的是它有效。

最佳答案

它是正则表达式元字符(字符串结尾),对其进行转义或添加参数regex=False:

df['b'] = df['b'].str.replace("\$sell","")
print (df)
a b
0 1 NaN
1 2 12
2 3 1

df['b'] = df['b'].str.replace("$sell","", regex=False)

如果还想要值 5,什么是数字,使用 Series.replace使用 regex=True 替换子字符串 - 不触及数值:

df['b'] = df['b'].replace("\$sell","", regex=True)

print (df['b'].apply(type))
0 <class 'int'>
1 <class 'str'>
2 <class 'str'>
Name: b, dtype: object

或者将列的所有数据转换为字符串:

df['b'] = df['b'].astype(str).str.replace("$sell","", regex=False)

print (df['b'].apply(type))
0 <class 'str'>
1 <class 'str'>
2 <class 'str'>
Name: b, dtype: object

为了获得更好的性能,如果没有缺失值是可能的,请使用列表理解:

df['b'] = [str(x).replace("$sell","") for x in  df['b']]

print (df)
a b
0 1 5
1 2 12
2 3 1

关于python - 无法替换 pandas 列中包含 $ 的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52554917/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com