如何使用loc
或iloc
在pd.DataFrame
中选择反向索引?
我尝试过df.loc[!my_index, my_feature]
但失败了。
而df.loc[[ind for ind in df.index.tolist() if ind not in my_index],my_feature]
看起来太枯燥了。 有更好的想法吗?
使用difference
函数:
df.loc[df.index.difference(my_index),my_feature]
或者使用numpy.setdiff1d
:
df.loc[np.setdiff1d(df.index, my_index),my_feature]
示例:
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
index.difference
。idx2 = df.index.difference(my_index)
set.difference
idx2 = set(df.index).difference(my_index) # note, order not guaranteed
df.loc[idx2, ...]
df.loc[df.index.difference(df_not.index)]
即可。 - Ufos