【发布时间】:2018-08-09 09:42:53
【问题描述】:
\r 符号为什么会在读取 csv 文件时使 pandas 出现错误?
例子:
test = pd.DataFrame(columns = ['id','text'])
test.id = [1,2,3]
test.text = ['Foo\rBar','Bar\rFoo','Foo\r\r\nBar']
test.to_csv('temp.csv',index = False)
test2 = pd.read_csv('temp.csv')
那么数据框如下:
测试:
id text
0 1 Foo\rBar
1 2 Bar\rFoo
2 3 Foo\r\r\nBar
测试2:
id text
0 1 Foo
1 Bar NaN
2 2 Bar
3 Foo NaN
4 3 Foo\r\r\nBar
请注意,在文本中添加\n 可防止转到另一行。知道发生了什么吗?以及如何防止这种行为?
请注意,它还会阻止使用pandas.to_pickle,因为它会损坏文件。生成包含以下错误的文件:
Error! ..\my_pickle.pkl is not UTF-8 encoded
Saving disabled.
See Console for more details.
【问题讨论】:
-
使用: test.to_csv('temp.csv',index = False,sep=',',line_terminator='\r') ,如果你想要与输入相同的输出
标签: python pandas csv character-encoding pickle