这是我的代码段。
import pandas as pd
import os
dpath = '//xxx//HEM'
for filename in os.listdir('//xxx//HEM'):
df = pd.read_csv(dpath + '/' + filename)
df = df['ab':'af'] #select required columns based on your requirement.
df["ab"] = pd.to_numeric(df["ab"]) # convert datatype of the column based on your need
df["af"] = pd.to_numeric(df["af"]) # convert datatype of the column based on your need
df1.append(df)
del df
df1.to_excel('test.xlsx')
在我正在读取的文件夹中的每个CSV表上,AB和AF列应为数字值。我收到以下错误。
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-17-c4c944eb874e> in <module>
4 for filename in os.listdir('//xxx//HEM'):
5 df = pd.read_csv(dpath + '/' + filename)
----> 6 df = df['ab':'af'] #select required columns based on your requirement.
7 df["ab"] = pd.to_numeric(df["ab"]) # convert datatype of the column based on your need
8 df1.append(df)
~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
2906
2907 # Do we have a slicer (on rows)?
-> 2908 indexer = convert_to_index_sliceable(self, key)
2909 if indexer is not None:
2910 return self._slice(indexer, axis=0)
~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\indexing.py in convert_to_index_sliceable(obj, key)
2454 idx = obj.index
2455 if isinstance(key, slice):
-> 2456 return idx._convert_slice_indexer(key, kind='getitem')
2457
2458 elif isinstance(key, compat.string_types):
~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\indexes\base.py in _convert_slice_indexer(self, key, kind)
2926 """
2927 if self.is_integer() or is_index_slice:
-> 2928 return slice(self._validate_indexer('slice', key.start, kind),
2929 self._validate_indexer('slice', key.stop, kind),
2930 self._validate_indexer('slice', key.step, kind))
~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\indexes\base.py in _validate_indexer(self, form, key, kind)
4708 pass
4709 elif kind in ['iloc', 'getitem']:
-> 4710 self._invalid_indexer(form, key)
4711 return key
4712
~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\indexes\base.py in _invalid_indexer(self, form, key)
3065 "indexers [{key}] of {kind}".format(
3066 form=form, klass=type(self), key=key,
-> 3067 kind=type(key)))
3068
3069 # --------------------------------------------------------------------
TypeError: cannot do slice indexing on <class 'pandas.core.indexes.range.RangeIndex'> with these indexers [ab] of <class 'str'>
我在做错什么吗?我猜它的数据格式是什么?