与这些索引器 [Moran,Mr.James] 的,python,pandas,slice"/>

首页 > 解决方案 > TypeError:无法对切片索引与这些索引器 [Moran,Mr.James] 的

问题描述

TypeError: cannot do slice indexing on with these indexer [Moran,Mr.James] of

这是学习录像带,我没有他们的资料。我添加了一些可以在我自己的数据中使用的数据。当我打印数据索引时它运行得很好,但是当我尝试从索引中切片数据时它无法运行并给我一些错误信息

我的数据/图像

import pandas as pd
# will return a new DataFrame that is indexed by the values in the specified column
# and will drop that cloumn from the DataFrame
# without the PannengerId dropped

# DataFrame来指定一个索引值

passenger_data = pd.read_csv('titanic/train.csv')
print(type(passanger_data) )
passenger_ticket = passanger_data.set_index('Name',drop=False) # 把ticket当成一个索引
print(passenger_ticket.index) # 打印index 值

#
# 目前怀疑是数据的问题,一下索引都失败了
# 具体问题详

print('\n\n\n\n=========================')
#Slice using either bracket notation or loc[]
passenger_data["Moran,Mr.James":"Sandstrom,Miss.Marguerite Rut"]

# Specific ticiket
passanger_data.loc["Moran,Mr.James":"Sandstrom,Miss.Marguerite Rut"]

# Select list of movies
tickets  = ["Sandstrom,Miss.Marguerite Rut","Moran,Mr.James","Rice,Master.Eugene"]
passenger_data.loc[tickets]

答案表格电脑

<class 'pandas.core.frame.DataFrame'>
Index(['Braund, Mr. Owen Harris',
       'Cumings, Mrs. John Bradley (Florence Briggs Thayer)',
       'Heikkinen, Miss. Laina',
       'Futrelle, Mrs. Jacques Heath (Lily May Peel)',
       'Allen, Mr. William Henry', 'Moran, Mr. James',
       'McCarthy, Mr. Timothy J', 'Palsson, Master. Gosta Leonard',
       'Johnson, Mrs. Oscar W (Elisabeth Vilhelmina Berg)',
       'Nasser, Mrs. Nicholas (Adele Achem)',
       ...
       'Markun, Mr. Johann', 'Dahlberg, Miss. Gerda Ulrika',
       'Banfield, Mr. Frederick James', 'Sutehall, Mr. Henry Jr',
       'Rice, Mrs. William (Margaret Norton)', 'Montvila, Rev. Juozas',
       'Graham, Miss. Margaret Edith',
       'Johnston, Miss. Catherine Helen "Carrie"', 'Behr, Mr. Karl Howell',
       'Dooley, Mr. Patrick'],
      dtype='object', name='Name', length=891)




=========================

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-24-a5b969b8a3ba> in <module>
     13 print('\n\n\n\n=========================')
     14 #Slice using either bracket notation or loc[]
---> 15 passenger_data["Moran,Mr.James":"Sandstrom,Miss.Marguerite Rut"]
     16 
     17 # Specific ticiket

F:\Software\PYTHON\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
   2959 
   2960         # Do we have a slicer (on rows)?
-> 2961         indexer = convert_to_index_sliceable(self, key)
   2962         if indexer is not None:
   2963             return self._slice(indexer, axis=0)

F:\Software\PYTHON\lib\site-packages\pandas\core\indexing.py in convert_to_index_sliceable(obj, key)
   2356     idx = obj.index
   2357     if isinstance(key, slice):
-> 2358         return idx._convert_slice_indexer(key, kind="getitem")
   2359 
   2360     elif isinstance(key, str):

F:\Software\PYTHON\lib\site-packages\pandas\core\indexes\base.py in _convert_slice_indexer(self, key, kind)
   3188             if self.is_integer() or is_index_slice:
   3189                 return slice(
-> 3190                     self._validate_indexer("slice", key.start, kind),
   3191                     self._validate_indexer("slice", key.stop, kind),
   3192                     self._validate_indexer("slice", key.step, kind),

F:\Software\PYTHON\lib\site-packages\pandas\core\indexes\base.py in _validate_indexer(self, form, key, kind)
   5069             pass
   5070         elif kind in ["iloc", "getitem"]:
-> 5071             self._invalid_indexer(form, key)
   5072         return key
   5073 

F:\Software\PYTHON\lib\site-packages\pandas\core\indexes\base.py in _invalid_indexer(self, form, key)
   3338             "cannot do {form} indexing on {klass} with these "
   3339             "indexers [{key}] of {kind}".format(
-> 3340                 form=form, klass=type(self), key=key, kind=type(key)
   3341             )
   3342         )

TypeError: cannot do slice indexing on <class 'pandas.core.indexes.range.RangeIndex'> with these indexers [Moran,Mr.James] of <class 'str'>

标签: pythonpandasslice

解决方案


您正在对错误的数据框进行切片:

passenger_data["Moran,Mr.James":"Sandstrom,Miss.Marguerite Rut"]

是你在做什么,但实际的索引被写入不同的数据帧

passenger_ticket["Moran,Mr.James":"Sandstrom,Miss.Marguerite Rut"]

或者也可能应该是

passenger_ticket.loc["Moran,Mr.James":"Sandstrom,Miss.Marguerite Rut"]

PS:正如@jezrael 已经提到的,我刚刚意识到......


推荐阅读