在 pandas 中按索引选择行的多个部分

问题描述 投票:0回答:3

我有带有 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],:]
但在最初的问题中我有数千行并且一些条目已经被删除,所以列出点不是一个选项。

python pandas slice
3个回答
12
投票

您可以使用

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]
选择标签
A
B
,包括
B
np.r_[A:B]
返回
A
B
的数组,排除
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

5
投票

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

0
投票

一个选项是 pyjanitor select_rows - 请注意选择是基于标签,而不是整数位置:

# pip install pyjanitor
import pandas as pd

df.select_rows(slice(11,13), slice(17,20))
    A  B
11  1  b
12  2  c
13  3  d
17  7  h
18  8  i
19  9  j
© www.soinside.com 2019 - 2024. All rights reserved.