尝试使用此处给出的解决方案后失败...我现在提出我的问题:
我有一个从多个txt文件导入的csv,目前dtype在所有列中都是str。 为了对我的数据进行排序,我需要一列再次使用int,但转换并不像我希望的那样工作。我正在使用熊猫。 我尝试了不同的方法。第一,用转换器加载数据:
df = pd.read_csv('501-1000.csv', sep='\t', header=None, index_col=False, names=cols, usecols=cols,converters={"PY":int})
并使用df["PY"].astype(int)
。在这两种情况下,我得到了ValueError: invalid literal for int() with base 10: 'BA'
由于我读到这与可以转换为整数的值有关,因此我尝试了df.dropna(subset=['PY'])
和df["PY"].fillna(0.0).astype(int)
结果没有改变。
关于如何解决这个问题的任何想法?可悲的是,手动检查我的行并不是一个选择 - 在我的测试文件中,也许,但它只是为了做很多数据。 尝试转换器时的完整回溯如下:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-4-d5ea8aa389dc> in <module>()
16 # load data; note dtype not set to str since there appear to be numeric columns
17 cols = ['TI', 'AB', 'PY', 'DI']
---> 18 df = pd.read_csv('501-1000.csv', sep='\t', header=None, index_col=False, names=cols, usecols=cols,converters={"PY":int})
19
20 # cycle through filename_dict, slice and export to csv
~\Anaconda3\lib\site-packages\pandas\io\parsers.py in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, escapechar, comment, encoding, dialect, tupleize_cols, error_bad_lines, warn_bad_lines, skipfooter, skip_footer, doublequote, delim_whitespace, as_recarray, compact_ints, use_unsigned, low_memory, buffer_lines, memory_map, float_precision)
653 skip_blank_lines=skip_blank_lines)
654
--> 655 return _read(filepath_or_buffer, kwds)
656
657 parser_f.__name__ = name
~\Anaconda3\lib\site-packages\pandas\io\parsers.py in _read(filepath_or_buffer, kwds)
409
410 try:
--> 411 data = parser.read(nrows)
412 finally:
413 parser.close()
~\Anaconda3\lib\site-packages\pandas\io\parsers.py in read(self, nrows)
1003 raise ValueError('skipfooter not supported for iteration')
1004
-> 1005 ret = self._engine.read(nrows)
1006
1007 if self.options.get('as_recarray'):
~\Anaconda3\lib\site-packages\pandas\io\parsers.py in read(self, nrows)
1746 def read(self, nrows=None):
1747 try:
-> 1748 data = self._reader.read(nrows)
1749 except StopIteration:
1750 if self._first_chunk:
pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader.read (pandas\_libs\parsers.c:10862)()
pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._read_low_memory (pandas\_libs\parsers.c:11138)()
pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._read_rows (pandas\_libs\parsers.c:12175)()
pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader._convert_column_data (pandas\_libs\parsers.c:14103)()
pandas/_libs/parsers.pyx in pandas._libs.parsers._apply_converter (pandas\_libs\parsers.c:30638)()
ValueError: invalid literal for int() with base 10: 'BA'
如果我错过了某些内容,请告诉我,我对编程都很陌生,这个网站和英语也不是我的第一语言。
答案 0 :(得分:1)
您已离场,需要省略converters
并使用带有参数errors='coerce'
的{{3}}进行转换,而不是将数字转换为NaN
s:
df = pd.read_csv('501-1000.csv',
sep='\t',
header=None,
index_col=False,
names=cols,
usecols=cols)
df["PY"] = pd.to_numeric(df["PY"], errors='coerce').fillna(0.0).astype(int)