[英]Pandas dataframe iloc with negation
我想将与列对应的行的值设置为特定值。 我只知道不应设置为该值的行的索引。 是否有内置技巧可以使用 iloc 执行此操作?
有没有像
df['I'].iloc[~rids] = 0
当然,做到这一点的一种方法是使用类似
set(range(len(df))).difference(rids)
但它看起来不是很好。 有什么建议吗?
使用DataFrame.loc
和Index.difference
of indexed real index values 和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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.