Pandas read_csv期望的列数错误,csv fi参差不齐

2024-03-28 16:28:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个csv文件,它有几百行26列,但是最后几列只有几行的值,它们位于文件的中间或结尾。当我尝试使用read_csv()读取它时,会得到以下错误。 值错误:应为23列,在第64行中为26列

我看不到在哪里显式地声明文件中的列数,也看不到它如何确定它认为文件应该有多少列。 垃圾场在下面

In [3]:

infile =open(easygui.fileopenbox(),"r")
pledge = read_csv(infile,parse_dates='true')


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-3-b35e7a16b389> in <module>()
      1 infile =open(easygui.fileopenbox(),"r")
      2 
----> 3 pledge = read_csv(infile,parse_dates='true')


C:\Python27\lib\site-packages\pandas-0.8.1-py2.7-win32.egg\pandas\io\parsers.pyc in read_csv(filepath_or_buffer, sep, dialect, header, index_col, names, skiprows, na_values, thousands, comment, parse_dates, keep_date_col, dayfirst, date_parser, nrows, iterator, chunksize, skip_footer, converters, verbose, delimiter, encoding, squeeze)
    234         kwds['delimiter'] = sep
    235 
--> 236     return _read(TextParser, filepath_or_buffer, kwds)
    237 
    238 @appender(_read_table_doc)

C:\Python27\lib\site-packages\pandas-0.8.1-py2.7-win32.egg\pandas\io\parsers.pyc in _read(cls, filepath_or_buffer, kwds)
    189         return parser
    190 
--> 191     return parser.get_chunk()
    192 
    193 @Appender(_read_csv_doc)

C:\Python27\lib\site-packages\pandas-0.8.1-py2.7-win32.egg\pandas\io\parsers.pyc in get_chunk(self, rows)
    779             msg = ('Expecting %d columns, got %d in row %d' %
    780                    (col_len, zip_len, row_num))
--> 781             raise ValueError(msg)
    782 
    783         data = dict((k, v) for k, v in izip(self.columns, zipped_content))

ValueError: Expecting 23 columns, got 26 in row 64

Tags: 文件csvinpandasreadparseegglib
3条回答

您还可以使用分隔符“^”加载CSV,将整个字符串加载到列中,然后使用split将字符串拆分为所需的分隔符。之后,执行concat以与原始数据帧合并(如果需要)。

temp=pd.read_csv('test.csv',sep='^',header=None,prefix='X')
temp2=temp.X0.str.split(',',expand=True)
del temp['X0']
temp=pd.concat([temp,temp2],axis=1)

给定解决方案的问题是,您必须知道所需的最大列数。我找不到解决此问题的直接函数,但您肯定可以编写一个def,它可以:

  1. 读所有的台词
  2. 把它分开
  3. 计算每行中的单词/元素数
  4. 存储最大字数/元素数
  5. 将该最大值放入names选项(由Roman Pekar建议)

以下是我为文件编写的def(函数):

def ragged_csv(filename):
    f=open(filename)
    max_n=0
    for line in f.readlines():
        words = len(line.split(' '))
        if words > max_n:
            max_n=words
    lines=pd.read_csv(filename,sep=' ',names=range(max_n))
    return lines

您可以使用names参数。例如,如果您有这样的csv文件:

1,2,1
2,3,4,2,3
1,2,3,3
1,2,3,4,5,6

试着读它,你会收到错误

>>> pd.read_csv(r'D:/Temp/tt.csv')
Traceback (most recent call last):
...
Expected 5 fields in line 4, saw 6

但是如果您传递names参数,您将得到结果:

>>> pd.read_csv(r'D:/Temp/tt.csv', names=list('abcdef'))
   a  b  c   d   e   f
0  1  2  1 NaN NaN NaN
1  2  3  4   2   3 NaN
2  1  2  3   3 NaN NaN
3  1  2  3   4   5   6

希望有帮助。

相关问题 更多 >