Pandas “解决错误”;分隔符必须是1个字符的字符串;将数据帧写入csv文件时

Pandas “解决错误”;分隔符必须是1个字符的字符串;将数据帧写入csv文件时,pandas,delimiter,Pandas,Delimiter,使用这个问题:作为一个模型,我编写了以下代码来创建csv文件: df.to_csv('/Users/Lab/Desktop/filteredwithheading.txt', sep='\s+', header=True) 但它返回以下错误: TypeError: "delimiter" must be an 1-character string TypeError .... ----> 1 df.to_csv(sep=',') TypeError: "de

使用这个问题:作为一个模型,我编写了以下代码来创建csv文件:

df.to_csv('/Users/Lab/Desktop/filteredwithheading.txt', sep='\s+', header=True)
但它返回以下错误:

TypeError: "delimiter" must be an 1-character string
TypeError ....              
----> 1 df.to_csv(sep=',')
TypeError: "delimiter" must be an 1-character string

我在这里查阅了相关文档,但我不知道我遗漏了什么,或者这个错误意味着什么。我还尝试在代码中使用(sep='\s'),但得到了相同的错误。

请注意,尽管此错误的解决方案是使用字符串字符而不是正则表达式,但熊猫在使用带有有效unicode字符的
from\uuuuu future\uuuuu导入unicode\u文本时也会引发此错误。截至2015-11-16版本0.16.2,此错误仍然是熊猫中的已知错误:

例如,其中df是数据帧:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import pandas as pd

df.to_csv(pdb_seq_fp, sep='\t', encoding='utf-8')
TypeError:“分隔符”必须是1个字符的字符串

使用带有指定编码(Python 3的默认utf-8)
-*-编码:utf-8-*-
将在pandas 0.16.2中解决此问题:(
b'\t'
)-我没有使用以前的版本或0.17.0进行测试

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import pandas as pd

df.to_csv(pdb_seq_fp, sep=b'\t', encoding='utf-8')

(请注意,对于版本0.13.0-??,有必要使用
pandas.compat import u
;但是到了0.16.2,字节文字就是最好的选择。)

如问题讨论()中所述,这不是熊猫问题,而是
python的csv模块
与python2.x的兼容性问题

解决此问题的解决方法是使用
str(..)
将分隔符括起来。例如,以下是如何重现问题,然后解决问题:

from __future__ import unicode_literals
import pandas as pd 
df = pd.DataFrame([['a', 'A'], ['b', 'B']])
df.to_csv(sep=',')
这将引发以下错误:

TypeError: "delimiter" must be an 1-character string
TypeError ....              
----> 1 df.to_csv(sep=',')
TypeError: "delimiter" must be an 1-character string
但是,以下内容将显示预期结果

from __future__ import unicode_literals
import pandas as pd 
df = pd.DataFrame([['a', 'A'], ['b', 'B']])
df.to_csv(sep=str(','))
输出:

',0,1\n0,a,A\n1,b,B\n'
在您的情况下,您应该按如下方式编辑代码:

df.to_csv('/Users/Lab/Desktop/filteredwithheading.txt', sep=str('\s+'), header=True)

代码创建文件,但不在其中写入数据。如果希望
sep
为空格,请使用
sep='''
。仅扩展bernie的注释,
\s+
是匹配1个或多个空格的正则表达式。它对于读取使用可变数量的空格作为分隔符的csv非常有用。您希望使用单空格分隔来编写csv。