python pandas read_csv无法识别制表符分隔文件中的\t

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45443406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:02:21  来源:igfitidea点击:

python pandas read_csv not recognizing \t in tab delimited file

pythonpandastab-delimited

提问by Omar

I'm trying to read in the following tab separated data into pandas:
test.txt:

我正在尝试将以下制表符分隔的数据读入熊猫:
test.txt:

col_a\tcol_b\tcol_c\tcol_d
4\t3\t2\t1  
4\t3\t2\t1 

I import test.txt as follows:

我导入 test.txt 如下:

pd.read_csv('test.txt',sep='\t')

The resulting dataframe has 1 column. The \t is not recognized as tab.

结果数据框有 1 列。\t 不被识别为制表符。

If I replace \t with a 'keyboard tab' the file is parsed correctly. I also tried replacing '\t with \t and /t and didn't have any luck.

如果我将 \t 替换为“键盘选项卡”,则会正确解析文件。我也尝试用 \t 和 /t 替换 '\t 并且没有任何运气。

Thanks in advance for your help.
Omar

在此先感谢您的帮助。
奥马尔

PS: Screenshot http://imgur.com/a/nXvW3

PS:截图http://imgur.com/a/nXvW3

回答by piRSquared

The \tin your file is an actual backslash followed by a t. It is nota tab. You're going to have to use some escape characters on your sepparameter.

\t您的文件是一个实际的反斜杠后跟一个t。它不是一个tab. 您将不得不在sep参数上使用一些转义字符。

pd.read_csv('test.txt', sep=r'\t', engine='python')

   col_a  col_b  col_c  col_d
0      4      3      2      1
1      4      3      2      1

Or

或者

pd.read_csv('test.txt', sep='\\t', engine='python')

   col_a  col_b  col_c  col_d
0      4      3      2      1
1      4      3      2      1


response to comment

回复评论

The ris indicating that it is a raw string and special characters should be interpreted the raw character. That is why in one solution I indicated that the string was raw and only had two backslashes. In the other, I had to escape each backslash with another backslash, leaving four backslashes.

r是表明它是一个原始字符串和特殊字符应该解释原始的字符。这就是为什么在一个解决方案中我指出字符串是原始的并且只有两个反斜杠。在另一个中,我不得不用另一个反斜杠来逃避每个反斜杠,留下四个反斜杠。