我解析了大量的 xml 文件以获取 pandas 数据框。我现在需要删除一些列进行数据分析。我无法在以前的问题中找到确切的错误。我用了 -
data = data["Rig Mode","Bit on Bottom","Block Position","Block Velocity",..]
并收到一条错误消息(完整的错误消息在帖子末尾)-
KeyError: 'Key length (22) exceeds index depth (2)'
所以我研究并去了这篇文章,这提到了lexsort depth
相关的错误,而我的正是上面发布的。我根据上面的帖子对索引进行了排序-
`data = data.sort_index(level=1)`
pd.__version__
'0.22.0'
Python version - 3.6.4
并得到完全相同的错误。下面我获取我的多索引详细信息 -
data.columns
#MultiIndex(levels=[['Bit on Bottom','Block Position', 'Block Velocity', 'Rig Mode',...], ['', '1/min', 'L/min', 'dega', ...]],
labels=[[38, 0, 2, 22, ...]],
names=['Description', 'Unit'])
这就是我在准备数据框时构建多索引的方式,现在的列标题被解析为数据集中的行 -
data.columns = pd.MultiIndex.from_arrays([data.iloc[0],data.iloc[1]], names = ['Description','Unit'])
data=data.iloc[2:]
#### complete error message:
> --------------------------------------------------------------------------- KeyError Traceback (most recent call
> last) <ipython-input-119-60ad57c2383f> in <module>()
> 3 "Continuous Survey Depth","Pump 1 Stroke Rate","Pump 2 Stroke Rate","Pump 3 Stroke Rate",
> 4 "Average Standpipe Pressure","Slips stat (1=Out,0=In)", "Weight on Bit","Mud Flow
> In","Time","Average Surface Torque",
> ----> 5 "MWD Turbine RPM"]
>
> ~\Anaconda3\lib\site-packages\pandas\core\frame.py in
> __getitem__(self, key) 2135 return self._getitem_frame(key) 2136 elif is_mi_columns:
> -> 2137 return self._getitem_multilevel(key) 2138 else: 2139 return self._getitem_column(key)
>
> ~\Anaconda3\lib\site-packages\pandas\core\frame.py in
> _getitem_multilevel(self, key) 2179 2180 def _getitem_multilevel(self, key):
> -> 2181 loc = self.columns.get_loc(key) 2182 if isinstance(loc, (slice, Series, np.ndarray, Index)): 2183
> new_columns = self.columns[loc]
>
> ~\Anaconda3\lib\site-packages\pandas\core\indexes\multi.py in
> get_loc(self, key, method) 2076 if self.nlevels < keylen:
> 2077 raise KeyError('Key length ({0}) exceeds index depth
> ({1})'
> -> 2078 ''.format(keylen, self.nlevels)) 2079 2080 if keylen == self.nlevels and self.is_unique:
>
> KeyError: 'Key length (22) exceeds index depth (2)'