Pandas 的SettingWithCopyWarning 报警
1、读取数据并对数据进行预处理操作¶
fpath='./datas/beijing_tianqi/beijing_tianqi_2018.csv'
df=pd.read_csv(fpath)
df.head()
df
import pandas as pd
df.loc[:,'bWendu']=df['bWendu'].str.replace('℃','').astype('int32')
df.loc[:,'yWendu']=df['yWendu'].str.replace('℃','').astype('int32')
df
2、复现错误
只选出3月份的数据用来分析
#只选出3月份的数据用来分析
condition=df['ymd'].str.startswith('2018-03')
设置温差
#设置温差
df[condition]['wen_cha']=df['bWendu']-df['yWendu']
值得注意的是报错:
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 发现:df[condition]['wen_cha']=df['bWendu']-df['yWendu']改句代码出错
这里我们也可以查看官网网站去完成差错:Indexing and selecting data — pandas 1.4.4 documentation (pydata.org)
查看是否修改成功
#查看是否修改成功
df[condition].head()
3、原因
发出警告的代码: df[condition]['wen_cha']=df['bWendu']-df['yWendu']
相当于: df.get(condition).set(wen_cha),第一步的get发出了报警
链式操作其实是两个步骤,先get 后set,get得到的dateframe可能是View也可能是Copy、Pandas发出警告
【先可以去官网查看原因】
核心: pandas的dataframe的修改写操作,只允许在dataframe上进行,一步到位
4、解决方法1
将get+set 的两步操作,改成set的一步操作
df.loc[condition,'wen_cha']=df['bWendu']-df['yWendu']
df.head()
df[condition].head()
5、解决方法2
如果需要预选筛选数据做后续的处理分析,使用copy复制Dataframe
df_month3=df[condition].copy()
df_month3.head()
df_month3['wen_cha']=df['bWendu']-df['yWendu']
df_month3.head()