简体   繁体   English

使用 pandas 替换 a.tsv 文件中的特殊字符

[英]replacing special characters in a .tsv file using pandas

I have a data frame I am trying to replace '[' and ']' for my.tsv file.我有一个数据框,我正在尝试为 my.tsv 文件替换 '[' 和 ']'。

cols_to_check = ['NUMBERS']
df[cols_to_check] = df[cols_to_check].str.replace({'[':''}, regex=True)
df.to_csv("output.tsv", sep='\t')

I'm not sure.我不确定。 The characters don't replace in output. output 中的字符不会替换。 They remain the same.它们保持不变。 Here is an example of input: ['1,2']这是一个输入示例:['1,2']

Output: '1,2' Output:'1,2'

It looks like pd.Series.str.replace uses two strings (or a compiled regex + callable) rather than a dictionary.看起来pd.Series.str.replace 使用两个字符串(或编译的正则表达式 + 可调用)而不是字典。 Further, if we are simply replacing one character (or string) with another, regex can be set to False.此外,如果我们只是简单地将一个字符(或字符串)替换为另一个,则可以将正则表达式设置为 False。

Try the following code instead:请尝试以下代码:

cols_to_check = ['NUMBERS']
df[cols_to_check] = df[cols_to_check].str.replace(pat='[', repl='', regex=False)
df.to_csv("output.tsv", sep='\t')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM