带有否定的熊猫数据框iloc

时间:2020-02-24 10:55:34

标签: python pandas indexing

我想将与一列相对应的行的值设置为特定值。我只知道不应该设置为该值的行的索引。有内置的技巧可以使用iloc做到这一点吗?

有没有类似的东西

df['I'].iloc[~rids] = 0

当然,一种方法是使用类似

set(range(len(df))).difference(rids)

但是看起来不是很好。有什么建议吗?

1 个答案:

答案 0 :(得分:3)

使用DataFrame.locIndex.difference的索引实数索引值和Index.difference

df = pd.DataFrame({'I' : ['A','B','C','D']}, index=list('abcd'))

indices = [0,3,1]

df.loc[df.index.difference(df.index[indices]), 'I'] = 0

或使用Index.isin

df.loc[~df.index.isin(df.index[indices]), 'I'] = 0

也可以使用位置为DataFrame.iloc的解决方案:

df.iloc[np.setdiff1d(np.arange(len(df)), indices), df.columns.get_loc('I')] = 0

print (df)
   I
a  A
b  B
c  0
d  D