英文:
Replace value in one column, if another column satisfies a condition
问题
如果 df['col1'] == 'A',那么 df['col2'].replace('X', 'Y', inplace=True)
我写了类似于 df[df['col1'] == 'A']['col2'].replace('X', 'Y', inplace=True) 的代码,但是它给我报错了,我找不到解决办法。
我正在尝试在满足另一列条件的情况下替换某列中的值。
英文:
I can't figure out how to write this
If df['col1']=='A' then df['col2'].replace('X','Y', inplace = True)
I write something like df[df['col1'] == 'A']['col2'].replace('X','Y', inplace = True) but it is giving me an error and I can't work out a solution to it.
I am trying to get a value in a column replaced, if a condition is met in another column
答案1
得分: 1
The problem is inplace=True
. You are trying that way to modify the "source" dataframe, but that dataframe is just a partial view (a slice) of another dataframe, so it is "read-only".
这个问题出在 inplace=True
。你试图使用这种方式修改“source”数据框,但该数据框只是另一个数据框的部分视图(一个切片),因此它是“只读”的。
It is a little bit like
df[(df.col1=='A') & (df.col2=='X')]['col2'] = 'Y'
这有点类似于
df[(df.col1=='A') & (df.col2=='X')]['col2'] = 'Y'
That would fail for the same reason: can't modify ['col2']
of dataframe df[(df.col1=='A') & (df.col2=='X')]
, since that dataframe is a slice of df
.
出于同样的原因,这将失败:无法修改数据框 df[(df.col1=='A') & (df.col2=='X')]
的 ['col2']
,因为该数据框是 df
的一个切片。
What you can do is
df.loc[(df.col1=='A') & (df.col2=='X'), 'col2'] = 'Y'
你可以这样做
df.loc[(df.col1=='A') & (df.col2=='X'), 'col2'] = 'Y'
英文:
The problem is inplace=True
. You are trying that way to modify the "source" dataframe, but that dataframe is just a partial view (a slice) of another dataframe, so it is "read-only".
It is a little bit like
df[(df.col1=='A') & (df.col2=='X')]['col2'] = 'Y'
That would fail for the same reason: can't modify ['col2']
of dataframe df[(df.col1=='A') & (df.col2=='X')]
, since that dataframe is a slice of df
.
What you can do is
df.loc[(df.col1=='A') & (df.col2=='X'), 'col2'] = 'Y'
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论