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

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

问题描述

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

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

我想要更优雅的方式:

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]]

注意:现在发出警告 不推荐使用 pandas.np 模块,并将在未来版本中从 Pandas 中删除.直接导入 numpy .为此,您可以 import numpy as np 然后按以下方式切片:

NOTE: this now gives a warning The pandas.np module is deprecated and will be removed from pandas in a future version. Import numpy directly instead. To do that, you can import numpy as np and then slice the following way:

df.iloc[np.r_[10:12, 25:28]]

这给出:

     a
10  20
11  21
25  35
26  36
27  37

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

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