【问题标题】:How to manage the special character \r in pandas dataframes如何管理熊猫数据框中的特殊字符 \r
【发布时间】: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


【解决方案1】:

尝试添加lineterminatorencoding参数:

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)。还要检查这个issue

【讨论】:

  • 对于 csv 文件,它可以正常工作,谢谢!您对泡菜文件有类似的解决方案吗?当我多次写入和读取文件时,pickle 会产生更快的性能。
【解决方案2】:

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

生成的 csv 应该如下所示:

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

或:

id  text
1   "Foo
Bar"
2   "Bar
Foo"
3   "Foo


Bar"

如果读者只将\n 视为换行符,则可以:

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

要读取 csv 数据,请务必告诉读者将字段解析为 quoted(这可能是默认值)。

解析器可能会尝试自动检测文件中换行符的类型(可能是\n\r\n 甚至是\r),也许这就是为什么如果\r\n 在未加引号的字段中。

【讨论】:

    猜你喜欢
    • 2018-02-02
    • 1970-01-01
    • 1970-01-01
    • 2021-03-29
    • 2022-07-22
    • 2019-08-09
    • 2015-05-13
    • 1970-01-01
    相关资源
    最近更新 更多