Select the inverse index in pd.Dataframe

后端 未结 3 511
我在风中等你
我在风中等你 2021-01-04 11:56

How to select the inverse index in pd.DataFrame by using loc or iloc?

I tried df.loc[!my_index,my_feature] but fail.

相关标签:
3条回答
  • 2021-01-04 12:38

    You may take advantage of index.difference.

    idx2 = df.index.difference(my_index)
    

    Or, set.difference

    idx2 = set(df.index).difference(my_index) # note, order not guaranteed
    

    df.loc[idx2, ...]
    
    0 讨论(0)
  • 2021-01-04 12:49

    Assuming my_index are the row indices you want to ignore, you could drop these where they exist in the dataframe df:

    df = df.drop(my_index, errors='ignore')

    0 讨论(0)
  • 2021-01-04 12:52

    Use difference:

    df.loc[df.index.difference(my_index),my_feature]
    

    Alternatively numpy.setdiff1d:

    df.loc[np.setdiff1d(df.index, my_index),my_feature]
    

    Sample:

    my_index = [5,7]
    df = pd.DataFrame({'A': ['a','a','a','b'], 'B': list(range(4)) }, index=[5,7,8,9])
    print (df)
       A  B
    5  a  0
    7  a  1
    8  a  2
    9  b  3
    
    print(df.loc[df.index.difference(my_index),'A'])
    8    a
    9    b
    Name: A, dtype: object
    
    0 讨论(0)
提交回复
热议问题