python pandas read_csv无法识别制表符分隔文件中的\ t [英] python pandas read_csv not recognizing \t in tab delimited file
问题描述
我正在尝试在以下标签中读取将数据分成大熊猫的内容:
test.txt:
I'm trying to read in the following tab separated data into pandas:
test.txt:
col_a\tcol_b\tcol_c\tcol_d
4\t3\t2\t1
4\t3\t2\t1
我按如下所示导入test.txt:
I import test.txt as follows:
pd.read_csv('test.txt',sep='\t')
结果数据框有1列. \ t不被识别为选项卡.
The resulting dataframe has 1 column. The \t is not recognized as tab.
如果将\ t替换为键盘选项卡",则文件将被正确解析.我也尝试用\ t和/t替换'\ 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.
在此先感谢您的帮助.
奥马尔
Thanks in advance for your help.
Omar
PS:屏幕截图 http://imgur.com/a/nXvW3
推荐答案
文件中的\t
是实际的反斜杠,后跟t
.这不是不是一个tab
.您将必须在sep
参数上使用一些转义符.
The \t
in your file is an actual backslash followed by a t
. It is not a tab
. You're going to have to use some escape characters on your sep
parameter.
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
或
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
r
表示它是原始字符串,应将特殊字符解释为原始字符.这就是为什么在一种解决方案中,我指出该字符串是原始字符串,并且只有两个反斜杠.在另一种情况下,我必须用另一个反斜杠转义每个反斜杠,剩下四个反斜杠.
The r
is 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.
这篇关于python pandas read_csv无法识别制表符分隔文件中的\ t的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!