简体   繁体   English

在 pd.Dataframe 中选择反向索引

[英]Select the inverse index in pd.Dataframe

How to select the inverse index in pd.DataFrame by using loc or iloc ?如何使用lociloc在 pd.DataFrame 中选择反向索引?

I tried df.loc[!my_index,my_feature] but fail.我试过df.loc[!my_index,my_feature]但失败了。

And df.loc[[ind for ind in df.index.tolist() if ind not in my_index],my_feature] looks too dull.df.loc[[ind for ind in df.index.tolist() if ind not in my_index],my_feature]看起来太单调了。 Any better idea?有什么更好的主意吗?

Use difference :使用difference

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

Alternatively numpy.setdiff1d :或者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

You may take advantage of index.difference .您可以利用index.difference

idx2 = df.index.difference(my_index)

Or, set.difference或者, 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