熊猫:从另一个数据框中复制列时出错

时间:2019-08-15 18:41:21

标签: python python-3.x pandas

我正在尝试将预测列从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.

有没有一种方法可以正确地执行列复制而不循环数据帧?

1 个答案:

答案 0 :(得分:0)

如果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)