加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-16 23:38:04 所属栏目:Python 来源:网络整理
导读:我想使用布尔掩码索引Pandas数据帧,然后根据整数索引在过滤后的数据帧的子集中设置一个值,并将此值反映在数据帧中.也就是说,如果这对数据框架有所了解,我会很高兴. 例: In [293]:df = pd.DataFrame({'a': [0,1,2,3,4,5,6,7],'b': [5,2],'c': [0,0]})mask =
我想使用布尔掩码索引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    0
3    0
6    0
Name: c,dtype: int64

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

In [294]:

df.loc[mask,'c'].iloc[0: 2]

Out[294]:

2    0
3    0
Name: c,dtype: int64

但不要分配:

In [295]:

df.loc[mask,'c'].iloc[0: 2] = 1

print(df)

   a  b  c
0  0  5  0
1  1  5  0
2  2  2  0
3  3  2  0
4  4  5  0
5  5  5  0
6  6  2  0
7  7  2  0

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

解决方法

这确实有效,但有点难看,基本上我们使用从掩码生成的索引并对loc进行额外调用:
In [57]:

df.loc[df.loc[mask,'c'].iloc[0:2].index,'c'] = 1
df
Out[57]:
   a  b  c
0  0  5  0
1  1  5  0
2  2  2  1
3  3  2  1
4  4  5  0
5  5  5  0
6  6  2  0
7  7  2  0

所以突破以上:

In [60]:
# take the index from the mask and iloc
df.loc[mask,'c'].iloc[0: 2]
Out[60]:
2    0
3    0
Name: c,dtype: int64
In [61]:
# call loc using this index,we can now use this to select column 'c' and set the value
df.loc[df.loc[mask,'c'].iloc[0:2].index]
Out[61]:
   a  b  c
2  2  2  0
3  3  2  0

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读