我需要正则表达式和正则表达式函数方面的帮助!!!我有一个由“;”分隔的 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=True
和 inplace=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/