【问题标题】:Slicing on Pandas Series Object with Index List Having Multiple Datatypes对具有多种数据类型的索引列表的 Pandas 系列对象进行切片
【发布时间】:2019-06-21 05:36:56
【问题描述】:

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

【问题讨论】:

  • 没关系,我找到了答案here

标签: python pandas slice


【解决方案1】:

如果不是在索引中混合类型的值,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),但找到整数(用于按位置选择)。

【讨论】:

    猜你喜欢
    • 2014-07-31
    • 2018-03-12
    • 2019-11-14
    • 2014-05-02
    • 2015-05-21
    • 2012-09-17
    • 1970-01-01
    • 2012-09-27
    相关资源
    最近更新 更多