如何向数据框的特定列的所有元素添加一个值

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

How to add a value to all elements of a certain column of a dataframe

问题

抱歉,由于您的请求,我只会翻译您提供的代码部分。以下是代码的翻译:

df[column_name] = df[column_name] + adjustment
df[column_name] = df[column_name] + adjustment

希望这有所帮助。如果您有其他需要,请随时提问。

英文:

One would think that the answer to this question would be something as simple as this:

df[column_name]=df[column_name] + adjustment

Sadly this does not work and after trying this we get this error message:

<ipython-input-29-9df0f3935efe>:25: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  df[column_name]=df[column_name] + adjustment

Sadly after trying using .loc and reading for 30 mins I am still unable to solve my trivial problem and thus I ask here since I am sure that what I am trying to do is very easy to solve with 1 line of code

Kind regards

答案1

得分: 0

以下是翻译好的部分:

一个可行但仍然会产生相同警告的解决方案如下:

df.loc[:,column_name]=df.loc[:,column_name].add(adjustment)

希望能看到一个不会产生这种警告的解决方案!

英文:

One solution that works but still gives the same warning is the following:

df.loc[:,column_name]=df.loc[:,column_name].add(adjustment)

Would be great to see a solution that does not produce such warning!

答案2

得分: 0

基于评论,警告是因为df是来自更大数据框的一个块而打印的。

考虑这个数据框main_df

  col1  col2
0    a     1
1    b     3
2    c     2
3    d     4
4    e     1

当你从这个数据框中获取一个块,例如 df = main_df.loc[1:3]

  col1  col2
1    b     3
2    c     2
3    d     4

然后当你尝试修改一列时会收到警告。例如 df['col2'] = df['col2'] + 10


你可以通过在修改列之前创建一个副本 df = df.copy() 来规避这个问题。

英文:

Based on the comment, the warning is printed because the df is a chunk from a bigger dataframe.

Consider this dataframe main_df:

  col1  col2
0    a     1
1    b     3
2    c     2
3    d     4
4    e     1

When you get a chunk from this dataframe, for example df = main_df.loc[1:3]:

  col1  col2
1    b     3
2    c     2
3    d     4

Then you get a warning when you try to modify a column. For example df['col2'] = df['col2'] + 10.


You can circumvent this making a copy df = df.copy() before modifying the column.

huangapple
  • 本文由 发表于 2023年7月27日 18:36:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76778894.html
匿名

发表评论

匿名网友

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

确定