替换一个列中的数值,如果另一个列满足条件。

huangapple go评论70阅读模式
英文:

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'

huangapple
  • 本文由 发表于 2023年6月8日 07:44:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76427738.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定