#Pandas的SettingWithCopyWarning报警
import pandas as pd
#读取Excel,并忽视前2个空行
df = pd.read_csv("D:\\python39\\pandas\\antlearnpandasmaster\\datas\\beijing_tianqi\\beijing_tianqi_2018.CSV")
#将温度字符串类型转换为int32
df.loc[:,'bWendu'] = df['bWendu'].str.replace('℃','').astype('int32')
df.loc[:,'yWendu'] = df['yWendu'].str.replace('℃','').astype('int32')
##复现报警
#只选出3月份的数据用于分析
condition = df.loc[df['ymd'].str.startswith("2018-03"),:]
##设置3月份温差
#df[condition]['wen_cha'] = df['bWendu']-df['yWendu']
###执行上一条代码时,出现错误,不能执行下去,其原因是
'''发出警告的代码df[condition]["wen_cha"] = df["bWendu"]-df["yWendu"]相当于: df.get(condition).set(wen_cha),第一步骤的get发出了报警
链式操作其实是两个步骤,先get后set,get得到的dataframe可能是view也可能是copy,pandas发出警告
官网文档: https:llpandas.pydata.org/pandas-docs/stable/user_guide/lindexing.htm#returning-a-view-versus-a-copy.
###核心要诀: pandas的dataframe的修改写操作,只允许在源dataframe上进行,一步到位'''
#df.loc[condition,'wen_cha'] =df['bWendu']-df['yWendu']
##解决方法
condition.loc[:,'wen_cha'] = condition['bWendu'] - condition['yWendu']
print(condition.head())
pandas 解决ValueError: Boolean array expected for the condition, not object 报错
最新推荐文章于 2022-11-15 11:24:56 发布