python pandas read_csv not recognizing \t in tab delimited file

北城以北 提交于 2019-11-29 20:34:53

问题


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 

I import test.txt as follows:

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

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

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: Screenshot http://imgur.com/a/nXvW3


回答1:


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

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 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.



来源:https://stackoverflow.com/questions/45443406/python-pandas-read-csv-not-recognizing-t-in-tab-delimited-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!