问题描述
我有一个数据框,我只想更改另一列满足特定条件的列的值.我目前正在尝试使用 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:
试图在数据帧的切片副本上设置值
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做布尔索引对,也就是如何提供行索引、列索引和布尔索引以正确的顺序和正确的语法.
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:更改通过列中的布尔索引选择的值而不会收到警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)