我有一个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
您还可以使用分隔符“^”加载CSV,将整个字符串加载到列中,然后使用split将字符串拆分为所需的分隔符。之后,执行concat以与原始数据帧合并(如果需要)。
给定解决方案的问题是,您必须知道所需的最大列数。我找不到解决此问题的直接函数,但您肯定可以编写一个def,它可以:
以下是我为文件编写的def(函数):
您可以使用
names
参数。例如,如果您有这样的csv文件:试着读它,你会收到错误
但是如果您传递
names
参数,您将得到结果:希望有帮助。
相关问题 更多 >
编程相关推荐