pandas 从数据框中的字符串中筛选出字符[重复]

z9gpfhce  于 2023-08-01  发布在  其他
关注(0)|答案(2)|浏览(90)

此问题已在此处有答案

Why doesn't modifying the iteration variable affect subsequent iterations?(10个答案)
Why doesn't calling a string method (such as .replace or .strip) modify (mutate) the string?(2个答案)
Pandas map column in place(2个答案)
How to replace text in a string column of a Pandas dataframe?(7个答案)
5天前关闭。
enter image description here
在上图中,我试图将字符串“200,000.00”更改为字符串“200000.00”。从上图中可以看到,我成功地更改了值字符串,但它没有在我的数据框中更新。为什么会这样呢?
我希望当我返回data时,数据框中的值将被更新。

wwwo4jvm

wwwo4jvm1#

看起来您正在尝试更改数据,即使您只更改了数据的迭代,这意味着实际的数据框永远不会更改。我认为解决这个问题的唯一方法是跟踪您在迭代中的位置,并在您要直接更改数据框的位置索引列表。你可以在下面看到我的解决方案:

def clean_data(data, bad_values):
    for i in range(len(data["SalaryUSD"])):
        string = data["SalaryUSD"][i]
        for ele in string:
            if ele in bad_values:
                data["SalaryUSD"][i]=string.replace(ele, "")
    return data

字符串
此外,在浏览了您提供的代码之后,我发现counter参数从未出现在您的代码中。我只是想确保你把它放回去,如果它是在你的完整代码中使用。

vuktfyat

vuktfyat2#

@Barmar方法可以扩展,这样你就可以使用以下方法删除bad_value列表中的所有字符:

bad_value = ['\$',',', ' ', '\[']   # extend to include all 'bad' values
pattern = '|'.join(bad_value)
data['Salary'] = data['SalaryUSD'].str.replace(pattern, '', regex = True)

字符串
请注意,在正则表达式中具有特殊含义的字符必须使用反斜杠\来“转义”。你可以查这些。您应该始终使用这种方法来处理Pandas DF,而不是循环。

相关问题