将数据框结果复制到Pandas中的SettingWithCopyWarning

时间:2018-10-02 09:43:14

标签: python pandas dataframe

我正在尝试向DataFrame Transactions_Meat中添加新列:

   Transactions_Meat['Avg_IPrice'] = Transactions_Meat['Rev'] / Transactions_Meat['Units_Sold']

导致此警告

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

Transactions_Meat是名为Transactions的DataFrame的副本:

Transactions_Meat = Transactions[Transactions['Category'] == 'Meat']

因此,我尝试使用.loc将我的方法更改为:

Transactions_Meat.loc[:,'Avg_IPrice'] = Transactions_Meat['Rev'] / Transactions_Meat['Units_Sold']

不幸的是,我仍然收到相同的警告。我访问了here中所述的熊猫文档。我还检查了stackoverflow-question,它已经在解决此问题。但是我无法摆脱警告。

是否可以使用DataFrame.loc方法删除警告?

1 个答案:

答案 0 :(得分:0)

此行不明确:

Transactions_Meat = Transactions[Transactions['Category'] == 'Meat']

如果要复制,请明确并使用pd.DataFrame.copy

Transactions_Meat = Transactions[Transactions['Category'] == 'Meat'].copy()

这应该删除后续的警告,并保证在操作Transactions时不会修改原始的Transactions_Meat数据框。