Python pandas 按多个索引范围对数据帧进行切片

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39393856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:58:46  来源:igfitidea点击:

Python pandas slice dataframe by multiple index ranges

pythonpandasindexingslice

提问by ragesz

What is the pythonic way to slice a dataframe by more index ranges (eg. by 10:12and 25:28)?

通过更多索引范围(例如 by10:1225:28)对数据帧进行切片的pythonic方法是什么?

I want this in a more elegant way:

我想要更优雅的方式:

df = pd.DataFrame({'a':range(10,100)})
df.iloc[[i for i in range(10,12)] + [i for i in range(25,28)]]

Result:

结果:

     a
10  20
11  21
25  35
26  36
27  37

Something like this would be more elegant:

这样的事情会更优雅:

df.iloc[(10:12, 25:28)]

回答by Jon Clements

You can use numpy's r_"slicing trick":

您可以使用 numpy 的r_“切片技巧”:

df = pd.DataFrame({'a':range(10,100)})
df.iloc[pd.np.r_[10:12, 25:28]]

Gives:

给出:

     a
10  20
11  21
25  35
26  36
27  37

回答by KevinOelen

You can take advantage of pandas isin function.

您可以利用Pandas的 isin 功能。

df = pd.DataFrame({'a':range(10,100)})
ls = [i for i in range(10,12)] + [i for i in range(25,28)]
df[df.index.isin(ls)]


    a
10  20
11  21
25  35
26  36
27  37