Pandas多索引df切片索引的多个子范围

2024-09-25 18:16:04 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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单独的行来完成,即:

^{pr2}$

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

有没有一种方法可以在一行中完成选择?一、 e.无需分别对每个片段进行切片,然后将所有片段重新组合成一个数据帧。在


Tags: 数据方法index切片ixsweeppr2sweep0001
1条回答
网友
1楼 · 发布于 2024-09-25 18:16:04

使用熊猫索引

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

您可以通过以下方式检索所需的标签:

^{pr2}$

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

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问答:Python Pandas slice multiindex by second level index (or any other level)

相关问题 更多 >