Select pandas 中索引的多个行部分

Select multiple sections of rows by index in pandas

我有一个带有 GPS 路径和​​一些属性的大型 DataFrame。路径的几个部分是我需要分析的部分。我只想将这些部分子集化为新的 DataFrame。我当时可以将一个部分子集化,但我的想法是拥有所有部分并拥有一个原始索引。

问题类似于:

import pandas as pd 
df = pd.DataFrame({'A':[0,1,2,3,4,5,6,7,8,9],'B':['a','b','c','d','e','f','g','h','i','j']},
                  index=range(10,20,))

我想要这样的东西:

cdf = df.loc[[11:13] & [17:20]] # SyntaxError: invalid syntax

期望的结果:

    A  B
11  1  b
12  2  c
13  3  d
17  7  h
18  8  i
19  9  j

我知道 cdf = df.loc[[11,12,13,17,18,19],:] 这个例子很简单,但在最初的问题中我有数千行并且一些条目已经被删除,所以列出点不是一个选项。

一种可能的解决方案 concat

cdf = pd.concat([df.loc[11:13], df.loc[17:20]])
print (cdf)
    A  B
11  1  b
12  2  c
13  3  d
17  7  h
18  8  i
19  9  j

range的另一个解决方案:

cdf = df.loc[list(range(11,14)) + list(range(17,20))]
print (cdf)
    A  B
11  1  b
12  2  c
13  3  d
17  7  h
18  8  i
19  9  j

您可以使用 np.r_ 连接切片:

In [16]: df.loc[np.r_[11:13, 17:20]]
Out[16]: 
    A  B
11  1  b
12  2  c
17  7  h
18  8  i
19  9  j

但是请注意, df.loc[A:B] 选择标签 AB,其中包含 Bnp.r_[A:B] returns AB 的数组,排除了 B。要包含 B,您需要使用 np.r_[A:B+1].

当传递切片时,例如 df.loc[A:B]df.loc 忽略不在 df.index 中的标签。相比之下,当传递数组时,例如 df.loc[np.r_[A:B]]df.loc 可能会为数组中不在 df.index.

中的每个值添加一个填充 NaN 的新行

因此,为了产生所需的结果,您需要调整切片的右端点并使用 isin 来测试 df.index:

中的成员资格
In [26]: df.loc[df.index.isin(np.r_[11:14, 17:21])]
Out[26]: 
    A  B
11  1  b
12  2  c
13  3  d
17  7  h
18  8  i
19  9  j