python - 使用具有多种数据类型的索引列表对 Pandas 系列对象进行切片

标签 python pandas slice

我刚刚开始学习 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/

相关文章:

python - Z3Py 中的替换

python - 从运行 fedora 的系统为我的 python 应用程序创建 debian 包

python - 为什么比较顺序对于这个 apply/lambda 不等式很重要?

python - 将 DataFrame 拆分为来自多列的组字典

R - 过滤行 - 将数据保留在两个重复值之间

python - 为什么 .loc 对切片具有包容性行为?

python - 为什么 pylint 为 numpy.ndarray.shape 返回 `unsubscriptable-object`?

python - 如何正确管理事件小部件,不失去它们的焦点或记住变量中的焦点

python - 循环更改 Pandas 数据框中列的顺序

go - 存储和检索接口(interface)的字节表示