我刚刚开始学习 Pandas,我不明白当索引列表包含多种类型的对象时切片是如何工作的。
import pandas as pd
arr = pd.Series([10, 20, 30, 40], index = [2, 3, 'six', 'eight'])
arr[2:3] #Output -- 30
arr[3:'six'] #TypeError: cannot do slice indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [3] of <class 'int'>
arr['six':'eight'] #Output -- 30, 40
arr[2:3] 不应该是 20 而 arr['six':'eight'] 不应该是 30 吗?
最佳答案
如果索引中没有混合类型的值,Pandas 的工作效果最好。
这里的通用解决方案是通过 Index.get_loc
获取每个索引的位置并选择Series.iloc
:
arr = pd.Series([10, 20, 30, 40], index = [2, 3, 'six', 'eight'])
print (arr.iloc[arr.index.get_loc(2):arr.index.get_loc(3)])
2 10
dtype: int64
print (arr.iloc[arr.index.get_loc(3):arr.index.get_loc('six')])
3 20
dtype: int64
print (arr.iloc[arr.index.get_loc('six'):arr.index.get_loc('eight')])
six 30
dtype: int64
您的解决方案部分有效:
首先,如果按两个整数进行选择,则 pandas 会按位置进行索引(如 iloc
):
print (arr[2:3])
six 30
dtype: int64
print (arr.iloc[2:3])
six 30
dtype: int64
如果通过两个标签进行选择,pandas 会选择类似的标签(如 loc
):
print (arr['six':'eight'])
six 30
eight 40
dtype: int64
print (arr.loc['six':'eight'])
six 30
eight 40
dtype: int64
未实现按混合值选择,因此引发错误 - pandas 尝试按标签选择(如 loc
),但找到整数(用于按位置选择)。
关于python - 使用具有多种数据类型的索引列表对 Pandas 系列对象进行切片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56697419/