pandas :在没有收到警告的情况下更改通过布尔索引在列中选择的值 [英] Pandas: Change values chosen by boolean indexing in a column without getting a warning

查看:44
本文介绍了 pandas :在没有收到警告的情况下更改通过布尔索引在列中选择的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,我只想更改另一列满足特定条件的列的那些值.我目前正在尝试使用 iloc 来执行此操作,但它可能无法正常工作,或者我会收到该烦人的警告:

I have a dataframe, I want to change only those values of a column where another column fulfills a certain condition. I'm trying to do this with iloc at the moment and it either does not work or I'm getting that annoying warning:

试图在DataFrame的切片副本上设置一个值

A value is trying to be set on a copy of a slice from a DataFrame

示例:

import pandas as pd
DF = pd.DataFrame({'A':[1,1,2,1,2,2,1,2,1],'B':['a','a','b','c','x','t','i','x','b']})

做其中之一

DF['B'].iloc[:][DF['A'] == 1] = 'X'

DF.iloc[:]['B'][DF['A'] == 1] = 'Y'

有效,但导致上述警告.

works, but leads to the warning above.

这也发出警告,但不起作用:

This one also gives a warning, but does not work:

DF.iloc[:][DF['A'] == 1]['B'] = 'Z'

我真的很困惑如何正确使用 loc iloc ix 进行布尔索引,即如何提供以正确的顺序并使用正确的语法的行索引,列索引和AND布尔索引.

I'm really confused about how to do boolean indexing using loc, iloc, and ix right, that is, how to provide row index, column index, AND boolean index in the right order and with the correct syntax.

有人可以帮我解决这个问题吗?

Can someone clear this up for me?

推荐答案

您正在链接自己的选择器,从而引发警告.将所选内容合并为一个.
使用 loc 代替

You are chaining you're selectors, leading to the warning. Consolidate the selection into one.
Use loc instead

DF.loc[DF['A'] == 1, 'B'] = 'X'
DF

这篇关于 pandas :在没有收到警告的情况下更改通过布尔索引在列中选择的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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