代码之家  ›  专栏  ›  技术社区  ›  Triceratops

从数据帧中选择不在子集中的索引

  •  0
  • Triceratops  · 技术社区  · 2 年前

    df = 
    test_idx sample value
    1        1      1.2
    1        2      -3.0
    1        3      4.7
    2        1      1.5
    2        2      2.8
    

    invalid_tests = [2,3,7] 无效。我想创建一个新的熊猫数据框架 cdf

    正如我在这里所做的那样,有一种直接的方法:

    valid_tests_idx = [] # indices of rows with valid tests
    for i in range(len(df)):
        if not df["test_idx"].iloc[i] in invalid_tests:
            valid_tests_idx.append(i)
    cdf = df.iloc[valid_tests_idx]
    

    它工作得很好,但我问是否有更优雅的方式或一行的方式来做到这一点。

    1 回复  |  直到 2 年前
        1
  •  0
  •   thomask    2 年前

    使用颚化符(~)运算符进行求反:

    df[~df.test_idx.isin(invalid_tests)]