【问题标题】:Pandas Multiindex df - slicing multiple sub-ranges of an indexPandas Multiindex df - 对索引的多个子范围进行切片
【发布时间】:2014-12-17 11:08:25
【问题描述】:

我有一个看起来像这样的数据框:

Sweep      Index
Sweep0001  0       -70.434570
           1       -67.626953
           2       -68.725586
           3       -70.556641
           4       -71.899414
           5       -69.946289
           6       -63.964844
           7       -73.974609
...
Sweep0039  79985   -63.964844
           79986   -66.406250
           79987   -67.993164
           79988   -68.237305
           79989   -66.894531
           79990   -71.411133

我想切出不同范围的扫描。

例如,我想要 Sweep0001 : Sweep0003、Sweep0009 : Sweep0015 等。

我知道我可以用 ix 在单独的行中执行此操作,即:

df.ix['Sweep0001':'Sweep0003']
df.ix['Sweep0009':'Sweep0015']

然后将它们重新组合到一个数据帧中(我这样做是为了平均扫描在一起,但我需要选择其中一些并删除其他)。

有没有办法在一行中进行选择? IE。无需单独切片每个部分,然后将所有部分重新组合到一个数据帧中。

【问题讨论】:

    标签: python pandas slice multi-index


    【解决方案1】:

    使用 Pandas 索引切片

    import pandas as pd
    idx = pd.IndexSlice
    df.loc[idx[["Sweep0001", "Sweep0002", ..., "Sweep0003", "Sweep0009", ..., "Sweep0015"]]
    

    您可以通过这种方式检索您想要的标签:

    list1 = df.index.get_level_values(0).unique()
    list2 = [x for x in list1]
    list3 = list2[1:4] #For your Sweep0001:Sweep0003
    list3.extend(list2[9:16]) #For you Sweep0009:Sweep0015
    df.loc[idx[list3]] #Note that you need one set of "[]"
                       #less around "list3" as this list comes
                       #by default with its own set of "[]".
    

    如果您还想按列切片,您可以使用:

    df.loc[idx[list3],:] #Same as above to include all columns.
    df.loc[idx[list3],:"column label"] #Returns data up to that "column label".
    

    有关切片的更多信息,请访问 Pandas 网站 (http://pandas.pydata.org/pandas-docs/stable/advanced.html#using-slicers) 或类似的 Stackoverflow Q/A:Python Pandas slice multiindex by second level index (or any other level)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-25
      • 2018-06-06
      • 2018-12-29
      • 2023-02-03
      • 2015-04-03
      • 2017-01-16
      • 2018-10-21
      • 2018-11-22
      相关资源
      最近更新 更多