如何在pandas中将两列相加而不触发SettingWithCopyWarning

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

How to add together two columns in pandas without receiving SettingWithCopyWarning

问题

尝试使用pandas将一列添加到另一列:

merged_df.loc[:, 'airline_name'] = merged_df.loc[:, 'airline_name'] + merged_df['airline_icao_unique_code']

但每次尝试时都会收到警告:

> SettingWithCopyWarning:
试图在DataFrame的切片副本上设置值。
请尝试使用.loc[row_indexer, col_indexer] = value来替代
详细信息请参阅文档:https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  self.obj[selected_item_labels] = value
进程以退出代码0完成

有没有办法在不触发此警告的情况下执行此操作?我已尝试更改语法并创建临时变量,但似乎无法使其正常工作。我还尝试使用.copy()函数,但仍然无法成功。

英文:

Trying to add add one column to another using pandas with:

merged_df.loc[:, 'airline_name'] = merged_df.loc[:, 'airline_name'] + merged_df['airline_icao_unique_code']

but every time I try I receive the warning :

> 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
self.obj[selected_item_labels] = value
Process finished with exit code 0

Is there any way to do this without triggering this warning? I have tried altering the syntax and creating temporary variables but I cant seem to get it to work. I have also tried using the .copy() function but still no dice.

答案1

得分: 1

这可能是因为merged_df是另一个DataFrame的子集。修复这个问题的最简单方法是在执行此操作之前使用.copy()

merged_df = merged_df.copy()
merged_df['airline_name'] = merged_df['airline_name'] + merged_df['airline_icao_unique_code']
英文:

This is likely due to merged_df being a subset of another DataFrame. The easiest way to fix this is to use .copy() before performing this operation:

merged_df = merged_df.copy()
merged_df['airline_name'] = merged_df['airline_name'] + merged_df['airline_icao_unique_code']

答案2

得分: 0

merged_df['airline_name'] = merged_df['airline_name'] + merged_df['airline_icao_unique_code']

英文:
merged_df['airline_name'] = merged_df['airline_name'] + merged_df['airline_icao_unique_code']

huangapple
  • 本文由 发表于 2023年3月4日 06:14:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/75632300.html
匿名

发表评论

匿名网友

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

确定