繁体   English   中英

在 pd.Dataframe 中选择反向索引

[英]Select the inverse index in pd.Dataframe

如何使用lociloc在 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, ...]

假设 my_index 是您要忽略的行索引,您可以将它们删除在数据帧 df 中存在的位置:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM