如何使用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
关于python - 选择pd.Dataframe中的逆向索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49854796/