【问题标题】:pandas: error when copy a column from another data frame熊猫:从另一个数据框中复制列时出错
【发布时间】:2019-12-22 04:26:36
【问题描述】:

我正在尝试将预测列从df_B 附加到df_A

df_A['prediction'] = df_B['prediction']

但该列未正确复制,我收到以下错误:

/Users/edamame/workspace/git/tensorplay/venv/lib/python3.7/site-packages/ipykernel_launcher.py:1: 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: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  """Entry point for launching an IPython kernel.

有没有办法在不循环数据框的情况下正确执行列复制?

【问题讨论】:

  • 您的方法正确。但是df_A 来自另一个数据框,即您可能在某个时候做了df_A = some_other_df[some_conditions]。现在,每当您更改 df_A 时,pandas 都会警告您说您正在更改 some_other_dfcopy,而不是 some_other_df 本身.要解决这个问题,您可以使用df_A = some_other_df[some_conditions].copy() 使其独立于之前的df
  • 我在这里回答了这个问题:stackoverflow.com/questions/57494760/…
  • 我喜欢的另一个修复是 df_A = some_other_df[condition][:] 虽然它不是很健壮

标签: python python-3.x pandas


【解决方案1】:

如果 df_A 和 df_B 的形状相同,则可以使用 Pandas 的 pd.concat() 功能。

import pandas as pd 

data_A = [['tom', 10], ['nick', 15], ['juli', 14]] 
df_A = pd.DataFrame(data_A, columns = ['Name', 'Age']) 

data_B = [['LA', "M"], ['NY', 'M'], ['SF', 'F']] 
df_B = pd.DataFrame(data_B, columns = ['City', 'Gender']) 

df_B = pd.concat([df_B, df_A[['Name']]], axis = 1)

【讨论】:

    猜你喜欢
    • 2018-08-03
    • 2013-12-04
    • 2019-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    相关资源
    最近更新 更多