python – 由布尔“loc”和后续“iloc”索引的Pandas

python – 由布尔“loc”和后续“iloc”索引的Pandas,第1张

概述我想使用布尔掩码索引Pandas数据帧,然后根据整数索引在过滤后的数据帧的子集中设置一个值,并将此值反映在数据帧中.也就是说,如果这对数据框架有所了解,我会很高兴. 例: In [293]:df = pd.DataFrame({'a': [0, 1, 2, 3, 4, 5, 6, 7], 'b': [5, 5, 2, 2, 5, 5, 2, 2], 我想使用布尔掩码索引Pandas数据帧,然后根据整数索引在过滤后的数据帧的子集中设置一个值,并将此值反映在数据帧中.也就是说,如果这对数据框架有所了解,我会很高兴.

例:

In [293]:df = pd.DataFrame({'a': [0,1,2,3,4,5,6,7],'b': [5,2],'c': [0,0]})mask = (df['a'] < 7) & (df['b'] == 2)df.loc[mask,'c']Out[293]:2    03    06    0name: c,dtype: int64

现在我想设置过滤后的数据帧中返回的前两个元素的值.将iloc链接到上面的loc调用上可以编制索引:

In [294]:df.loc[mask,'c'].iloc[0: 2]Out[294]:2    03    0name: c,dtype: int64

但不要分配:

In [295]:df.loc[mask,'c'].iloc[0: 2] = 1print(df)   a  b  c0  0  5  01  1  5  02  2  2  03  3  2  04  4  5  05  5  5  06  6  2  07  7  2  0

使赋值与切片的长度相同(即= [1,1])也不起作用.有没有办法分配这些值?

解决方法 这确实有效,但有点难看,基本上我们使用从掩码生成的索引并对loc进行额外调用:
In [57]:df.loc[df.loc[mask,'c'].iloc[0:2].index,'c'] = 1dfOut[57]:   a  b  c0  0  5  01  1  5  02  2  2  13  3  2  14  4  5  05  5  5  06  6  2  07  7  2  0

所以突破以上:

In [60]:# take the index from the mask and ilocdf.loc[mask,'c'].iloc[0: 2]Out[60]:2    03    0name: c,dtype: int64In [61]:# call loc using this index,we can Now use this to select column 'c' and set the valuedf.loc[df.loc[mask,'c'].iloc[0:2].index]Out[61]:   a  b  c2  2  2  03  3  2  0
总结

以上是内存溢出为你收集整理的python – 由布尔“loc”和后续“iloc”索引的Pandas全部内容,希望文章能够帮你解决python – 由布尔“loc”和后续“iloc”索引的Pandas所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1207466.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)

保存