将csv文件读入pandas失败

时间:2017-08-15 10:12:47

标签: python pandas

我有一个通过将Tableau表导出到csv生成的csv文件,但我无法在Python中打开它。

我曾尝试使用pd.read_csv,但失败了。

import pandas as pd

#path to file
path = "tableau_crosstab.csv"

data = pd.read_csv(path, encoding="ISO-8859-1") 

这适用于在文件中读取,但结果只是行数,每行一个字符,帧头部有一些奇怪的字符。

ÿþd
o    
m    
a    
i

等等。当我尝试在Excel中导入文件时,我必须选择制表符作为分隔符,但是当我在这里试图它失败时

import pandas as pd

#path to file
path = "tableau_crosstab.csv"

data = pd.read_csv(path, encoding="ISO-8859-1", sep='\t') 

CParserError:标记数据时出错。 C错误:第7行预期有1个字段,见2

我确实尝试使用编解码器打开文件,然后它说编码是' cp1252',但是使用它,因为编码也失败了。

我也尝试使用utf-8读取它,但也失败了。 我对如何解决这个问题的想法不足。

如果有人可以查看该文件的副本,这里有一个链接 http://www.mediafire.com/file/6dtxo2deczwy3u2/tableau_crosstab.csv

1 个答案:

答案 0 :(得分:3)

您具有专门的unicode BOM utf-16LE

尝试

data = pd.read_csv(path, encoding="utf-16", sep='\t') 

您看到的有趣字符:ÿþ对应于十六进制FF FE,它是unicode-16 little endian字节顺序标记。如果您看到维基百科页面,则会显示所有各种字节顺序标记

我在阅读你的csv时得到​​以下信息:

In[4]:
data = pd.read_csv(r'C:\tableau_crosstab.csv', encoding='utf-16', sep='\t')
data

Out[4]: 
       domain Month of date impressions clicks
0    test1.no        jun.17     725 676    633
1    test1.no        mai.17     422 995    456
2    test1.no        apr.17     241 102    316
3    test1.no        mar.17     295 157    260
4    test1.no        feb.17     122 902    198
5    test1.no        jan.17     137 972    201
6    test1.no        des.16     274 435    361
7   test2.com        jun.17   3 083 373  1 638
8   test2.com        mai.17   3 370 620  2 036
9   test2.com        apr.17   2 388 933  1 483
10  test2.com        mar.17   2 410 675  1 581
11  test2.com        feb.17   2 311 952  1 682
12  test2.com        jan.17   1 184 787    874
13  test2.com        des.16   2 118 594  1 738
14  test3.com        jun.17     411 456     41
15  test3.com        mai.17     342 048     87
16  test3.com        apr.17     197 058    108
17  test3.com        mar.17     288 949    156
18  test3.com        feb.17     230 970    130
19  test3.com        jan.17     388 032    115
20  test3.com        des.16   1 693 442    166
21   test4.no        jun.17     521 790    683
22   test4.no        mai.17     438 037    541
23   test4.no        apr.17     618 282  1 042
24   test4.no        mar.17     576 413    956
25   test4.no        feb.17     451 248    636
26   test4.no        jan.17     293 217    471
27   test4.no        des.16     641 491    978