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

rag*_*esz 17 python indexing slice pandas

什么是通过更多索引范围(例如by 10:1225:28)对数据帧进行切片的pythonic方法?我希望以更优雅的方式:

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

结果:

     a
10  20
11  21
25  35
26  36
27  37
Run Code Online (Sandbox Code Playgroud)

像这样的东西会更优雅:

df.iloc[(10:12, 25:28)]
Run Code Online (Sandbox Code Playgroud)

谢谢!

Jon*_*nts 45

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

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

得到:

     a
10  20
11  21
25  35
26  36
27  37
Run Code Online (Sandbox Code Playgroud)

  • 有一点需要注意:要获得负索引(即相当于`df.iloc [-2:]`),必须包含一个零:`df.iloc [pd.np.r _ [:2,-2:0 ]]` (4认同)

Kev*_*len 8

您可以利用 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
Run Code Online (Sandbox Code Playgroud)