在pd.Dataframe中选择反索引 [英] Select the inverse index in pd.Dataframe

查看:117
本文介绍了在pd.Dataframe中选择反索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用lociloc在pd.DataFrame中选择反索引?

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

我尝试了df.loc[!my_index,my_feature],但是失败了.

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

df.loc[[ind for ind in df.index.tolist() if ind not in 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. Any better idea?

推荐答案

使用 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

这篇关于在pd.Dataframe中选择反索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆