【问题标题】:pandas: slicing along first level of multiindexpandas:沿多索引的第一级切片
【发布时间】:2018-03-13 22:18:20
【问题描述】:

我设置了一个带有两个索引的 DataFrame。但是切片的行为并不像预期的那样。 我意识到这是一个非常基本的问题,所以我搜索了类似的问题:

pandas: slice a MultiIndex by range of secondary index

Python Pandas slice multiindex by second level index (or any other level)

我也看了对应的documentation

奇怪的是,所提出的解决方案都不适合我。 我已经建立了一个简单的例子来展示这个问题:

# this is my DataFrame
frame = pd.DataFrame([
{"a":1, "b":1, "c":"11"},
{"a":1, "b":2, "c":"12"},
{"a":2, "b":1, "c":"21"},
{"a":2, "b":2, "c":"22"},
{"a":3, "b":1, "c":"31"},
{"a":3, "b":2, "c":"32"}])

# now set a and b as multiindex
frame = frame.set_index(["a","b"])

现在我正在尝试不同的切片框架的方法。 前两行有效,第三行抛出异常:

# selecting a specific cell works
frame.loc[1,2]

# slicing along the second index works
frame.loc[1,:]

# slicing along the first doesn't work
frame.loc[:,1]

这是一个类型错误:

TypeError: cannot do label indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [1] of <class 'int'>

解决方案 1:使用切片元组

这是在这个问题中提出的:pandas: slice a MultiIndex by range of secondary index

确实,您可以为每个级别传递一个切片

但这对我不起作用,会产生与上面相同的类型错误。

frame.loc[(slice(1,2), 1)]

解决方案 2:使用 IndexSlice

Python Pandas slice multiindex by second level index (or any other level)

使用索引器对任意维度的任意值进行切片

同样,这对我不起作用,它会产生相同类型的错误。

frame.loc[pd.IndexSlice[:,2]]

我不明白这种类型错误是如何产生的。毕竟我可以使用整数来选择特定的单元格,并且沿第二维的范围可以正常工作。 谷歌搜索我的具体错误信息并没有真正帮助。 例如,这里有人尝试使用整数沿浮点类型的索引进行切片:https://github.com/pandas-dev/pandas/issues/12333

我尝试将我的索引显式转换为 int,也许 numpy 后端默认将所有内容存储为浮点数? 但这并没有改变任何东西,之后出现了与上面相同的错误:

frame["a"]=frame["a"].apply(lambda x : int(x))
frame["b"]=frame["b"].apply(lambda x : int(x))

type(frame["b"][0])  # it's numpy.int64

【问题讨论】:

    标签: python pandas numpy dataframe


    【解决方案1】:

    IIUC 在索引多索引 DF 时,您只需为列指定 :

    In [40]: frame.loc[pd.IndexSlice[:,2], :]
    Out[40]:
          c
    a b
    1 2  12
    2 2  22
    3 2  32
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-20
      • 2015-03-16
      • 2014-07-30
      • 2021-08-25
      • 2016-12-12
      • 2016-02-21
      • 2016-01-16
      • 2017-08-22
      相关资源
      最近更新 更多