Python 如何管理数据帧中的特殊字符\r

Python 如何管理数据帧中的特殊字符\r,python,pandas,csv,character-encoding,pickle,Python,Pandas,Csv,Character Encoding,Pickle,为什么符号\r在读取csv文件时会出现错误 例如: 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') 然后,数据帧如下所示: 测试: 测试2: id text 0

为什么符号
\r
在读取csv文件时会出现错误

例如:

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')
然后,数据帧如下所示:

测试:

测试2:

    id      text
0   1       Foo
1   Bar     NaN
2   2       Bar
3   Foo     NaN
4   3       Foo\r\r\nBar
请注意,将
\n
添加到文本中会阻止转到另一行。知道发生了什么吗?如何防止这种行为

请注意,IIT还阻止使用
pandas.to_pickle
,因为它会损坏文件。生成包含以下错误的文件:

Error! ..\my_pickle.pkl is not UTF-8 encoded
Saving disabled.
See Console for more details.

尝试添加
行终止符
编码
参数:

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, line_terminator='\n', encoding='utf-8')
test2 = pd.read_csv('temp.csv', lineterminator='\n', encoding='utf-8')
测试和测试2:

    id  text
0   1   Foo\rBar
1   2   Bar\rFoo
2   3   Foo\r\r\nBar

它对我来说很好,但也许这只是Windows的问题(我有MacBook)。同时检查此项。

为了获得有效的csv数据,所有包含换行符的字段都应该用双引号括起来

生成的csv应如下所示:

id  text
1   "Foo\rBar"
2   "Bar\rFoo"
3   "Foo\r\r\nBar"
或:

如果读取器仅将
\n
视为换行符,则可以执行以下操作:

id  text
1   Foo\rBar
2   Bar\rFoo
3   "Foo\r\r\nBar"
要读取csv数据,请确保告诉读者将字段解析为
quoted
(可能是默认值)


解析器可能会尝试自动检测文件中换行符的类型(可能是
\n
\r\n
甚至
\r
),这可能就是为什么如果在非引号字段中存在
\r
\n
的组合,您可能会得到意外结果的原因。

使用:test.to\u csv('temp.csv',index=False,sep=',',line_terminator='\r'),如果您想要与inputIt相同的输出,csv文件也可以这样工作。谢谢!对于pickle文件,您有类似的解决方案吗?由于我多次写入和读取文件,pickle产生更快的性能。
id  text
1   "Foo
Bar"
2   "Bar
Foo"
3   "Foo


Bar"
id  text
1   Foo\rBar
2   Bar\rFoo
3   "Foo\r\r\nBar"