【问题标题】:Elements of pandas not in an index list [duplicate]不在索引列表中的熊猫元素[重复]
【发布时间】:2018-10-13 21:20:08
【问题描述】:

如何获取不在给定索引列表中的 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)...

感谢您的帮助!

【问题讨论】:

    标签: python pandas indexing


    【解决方案1】:

    使用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
    

    【讨论】:

      【解决方案2】:

      一种方法是使用set:

      res = set(A.index) - set(ind)
      
      {0, 4, 5, 6, 7, 8, 9}
      

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

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

      【讨论】:

      • 此解决方案还删除重复项
      猜你喜欢
      • 2013-08-22
      • 1970-01-01
      • 2020-03-13
      • 2018-07-06
      • 2020-10-13
      • 1970-01-01
      相关资源
      最近更新 更多