Python中DataFrame object类型列相乘添加新列的警告解决
解决Pandas设置新列时的视图/副本警告问题
问题背景
这是Udemy训练营课程(第76天)的问题,我是Python新手,若表述不当请见谅。我有一个包含10列的apps.csv文件,各列数据类型如下:
App object Category object Rating float64 Reviews int64 Size_MBs float64 Installs object Type object Price object Content_Rating object Genres object dtype: object
需求与现有代码
我希望将文件中的Price和Installs列相乘,添加名为Revenue_Estimate的新列,编写代码如下:
import pandas as pd df=pd.read_csv('apps.csv') clean_df=df.dropna() clean_df.loc[:, "Installs"] = clean_df.loc[:, "Installs"].astype(str).str.replace(",", "") clean_df.loc[:, "Installs"] = pd.to_numeric(clean_df.loc[:, "Installs"]) clean_df.loc[:,'Price'] = clean_df.loc[:,'Price'].astype(str).str.replace('$', "") clean_df.loc[:, "Price"] = pd.to_numeric(clean_df.loc[:,'Price']) #Line 8: clean_df['Revenue_Estimate']= clean_df.Installs * clean_df.Price
遇到的警告
执行上述代码时出现如下警告:
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: clean_df['Revenue_Estimate']= clean_df.Installs * clean_df.Price
我也尝试了以下代码,仍无法解决:
df_apps_clean['Revenue_Estimate'] = df_apps_clean.Installs.mul(df_apps_clean.Price)
对应的警告信息:
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: clean_df['Revenue_Estimate'] = clean_df.Installs.mul(clean_df.Price)
解决方案
问题出在clean_df = df.dropna()这一行:dropna()默认返回的是原DataFrame的视图而非独立副本,后续对clean_df的修改操作会触发Pandas的视图/副本警告。
解决方法很简单,只需要在dropna()时显式指定返回副本,或者直接对结果调用.copy():
修改后的完整代码
import pandas as pd df=pd.read_csv('apps.csv') # 方法1:dropna时指定copy=True clean_df=df.dropna(copy=True) # 或者方法2:显式复制 # clean_df=df.dropna().copy() clean_df.loc[:, "Installs"] = clean_df.loc[:, "Installs"].astype(str).str.replace(",", "") clean_df.loc[:, "Installs"] = pd.to_numeric(clean_df.loc[:, "Installs"]) clean_df.loc[:,'Price'] = clean_df.loc[:,'Price'].astype(str).str.replace('$', "") clean_df.loc[:, "Price"] = pd.to_numeric(clean_df.loc[:,'Price']) # 现在添加新列不会再触发警告 clean_df['Revenue_Estimate']= clean_df.Installs * clean_df.Price
这样修改后,clean_df就变成了独立的DataFrame副本,后续的所有修改操作都不会再触发视图/副本相关的警告。
内容的提问来源于stack exchange,提问作者Venkat Karthik
相关产品推荐
相关产品推荐

