Python pandas按多个索引范围切片数据帧 [英] Python pandas slice dataframe by multiple index ranges

查看:993
本文介绍了Python pandas按多个索引范围切片数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用更多索引范围对数据帧进行切片的pythonic方法是什么(例如, 10:12 25:28 )?
我想以更优雅的方式:

What is the pythonic way to slice a dataframe by more index ranges (eg. by 10:12 and 25:28)? 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)]]

结果:

     a
10  20
11  21
25  35
26  36
27  37

这样的事情会更优雅:

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

谢谢!

推荐答案

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

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

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

给出:

     a
10  20
11  21
25  35
26  36
27  37

这篇关于Python pandas按多个索引范围切片数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆