不在索引列表中的pandas元素

4

如何获取不在给定索引列表中的pandas DataFrame元素?

以下是一个简单的示例:

import pandas as pd
import numpy as np

A = np.linspace(10, 100, 10)

A = pd.DataFrame(A, columns=["A"])
ind = [x for x in range(1, 4)]
print(A.iloc[ind])

所以举个例子,现在我想获取所有不在ind中的元素(索引为0,5,6,7,8,9)...
感谢帮助!
2个回答

6

使用 Index.difference 方法:

print(A.iloc[A.index.difference(ind)])
       A
0   10.0
4   50.0
5   60.0
6   70.0
7   80.0
8   90.0
9  100.0

3

一种方法是使用set

res = set(A.index) - set(ind)

{0, 4, 5, 6, 7, 8, 9}

这是对于 set(A.index).difference(set(ind)) 的语法糖。

正如指出的那样,这也会从 A.index 中删除重复项。


2
此解决方案还可以去除重复项。 - Brendan Frick

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接