python - Pandas DF : how to replace '-' by '_' with separators (; CSV format)

标签 python regex pandas csv

我需要正则表达式和正则表达式函数方面的帮助!!!我有一个由“;”分隔的 CSV 文件并且需要将 - 替换为 _。数据如下所示:

79             80;0;RueSaint_Hilaire;Locale;15-25;1;1             
80              81;0;RueSaint_Hilaire;Locale;5-10;5;5             
81                   82;0;RueTaillon;Locale;10-15;1;1             
82                   83;0;RueTanguay;Locale;10-15;2;2             
83                   84;0;RueTanguay;Locale;15-25;2;2             
84                    85;0;RueTanguay;Locale;5-10;3;3  

我需要将 15-25 替换为 15_25。

到目前为止我已经试过了:

df.replace('-','_', inplace=True)

或者这个:

df_obj = df.select_dtypes(['object'])
df[df_obj.columns] = df_obj.apply(lambda x: x.str.strip())
df.replace('-','_', inplace=True)
print(df)

没有任何成功。任何正则表达式或替换向导都可以解决这个小问题吗?

非常感谢!

最佳答案

默认情况下 regex=False。因此,在您现有的代码中使用正则表达式替换为 regex=Trueinplace=True。参见 replace

df.replace('-', '_',regex=True, inplace=True)
print(df)

关于python - Pandas DF : how to replace '-' by '_' with separators (; CSV format),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55107308/

相关文章:

python - 在 python 中读取没有标题的 .img 医学图像

python - 使用 .groupby 和 .transform 进行聚合

python - 搜索包含数字python的字符串

python - ValueError : Location based indexing can only have [integer, 整数切片,类似于整数, bool 数组]类型

python - 对 pandas 数据框中的条件求和列

python - 当我单击按钮时,打开新表格并写一些东西

python - 通过查询更新不起作用, Elasticsearch python

java - 如何删除字符串中 HTML 标记中的所有 HTML 属性

python - 如何在Python中搜索一组字符串中的一个

python - 循环遍历 python 字典并操作每个值