我正在尝试向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方法删除警告?
答案 0 :(得分:0)
此行不明确:
Transactions_Meat = Transactions[Transactions['Category'] == 'Meat']
如果要复制,请明确并使用pd.DataFrame.copy
:
Transactions_Meat = Transactions[Transactions['Category'] == 'Meat'].copy()
这应该删除后续的警告,并保证在操作Transactions
时不会修改原始的Transactions_Meat
数据框。