【问题标题】:Pandas select by index and filter by boolean maskPandas 按索引选择并按布尔掩码过滤
【发布时间】:2019-12-07 10:08:37
【问题描述】:

我有以下数据框

import pandas as pd

test = pd.DataFrame()
test['1'] = [12,23,34, 45]
test['blah'] = ['a', 'b', 'c', 'e']
test['a'] = [None, 1, 1, None]

我希望能够使用布尔掩码过滤和索引(我在其他地方定义)来选择它,例如

test['a'] == 1  # filter

ind = pd.RangeIndex(start=0, stop=4, step=2)  # pd index object

如何将它们一起使用?我要选择的内容(来自索引 2,4)

index   1       blah  a
2       34      c     1.0

我试过了,但是 pandas 不明白如何同时使用索引和布尔掩码

test[test.loc[ind,:] & test['a'] == 1] # Don't work

【问题讨论】:

    标签: python pandas filtering


    【解决方案1】:

    你可以使用numpy.intersect1d:

    arr = np.intersect1d(test.index[test['a'].eq(1)], ind)
    #alternative arr = set(test.index[test['a'].eq(1)]).intersection(ind) 
    
    print(test.loc[arr, :])
        1 blah    a
    2  34    c  1.0
    

    【讨论】:

      【解决方案2】:

      你可以这样做:

      test.loc[(test.index.isin(ind)) & (test['a'] == 1)]
      

      输出:

          1 blah    a
      2  34    c  1.0
      

      【讨论】:

        【解决方案3】:

        这是另一种方式:

        test.loc[ind & test.index.where(test['a'] == 1)]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-08-05
          • 2013-12-12
          • 2022-06-20
          • 1970-01-01
          • 2021-07-08
          • 2019-12-06
          相关资源
          最近更新 更多