Pandas的SettingWithCopyWarning问题

Pandas的SettingWithCopyWarning问题

前言

Windows平台
python3.6


具体问题:我们在读取数据,进行增加列时出现了SettingWithCopyWarning相关的警告

一、读取数据

"""
 author:jjk
 datetime:2020/01/31
 coding:utf-8
 project name:test/pandas
 Program function: Pandas的SettingWithCopyWarning
"""
import pandas as pd
# 0 读取数据
fpath = "./datas/beijing_tianqi/beijing_tianqi_2018.csv"
df = pd.read_csv(fpath)
df.head()

在这里插入图片描述

二、数据简单清洗处理

好吧,我们先简单的处理一下数据:

# 替换掉温度的后缀℃
df.loc[:,'bWendu'] = df['bWendu'].str.replace('℃','').astype('int32')
df.loc[:,'yWendu'] = df['yWendu'].str.replace('℃','').astype('int32')

好嘛,处理完之后,咋们再看一下最新的数据格式:
在这里插入图片描述

三、复现

# 1、复现
# 只选出3月份的数据用于分析
condition = df['ymd'].str.startswith('2018-03')
# 设置温度差
df[condition]['wen_cha'] = df['bWendu']-df['yWendu']

报错:

F:\Anaconda\anaconda_install\lib\site-packages\ipykernel_launcher.py:5: 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
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy

在这里插入图片描述
这就是我们本文的核心:
发出警告的代码:df.condition = df['bWendu']-df['yWendu']
相当于:df.get(condition).set(wen_cha)第一步的get发出的警告。
解释
链式操作其实是两个步骤,先get后set,get得到的dataframe可能是view也可能是copy,pandas发出警告。核心要诀:pandas的dataframe的修改写操作,只允许在源dataframe上进行,一步到位。

四、解决方法

4.1 解决方法1

# 将get+Set的两步操作,改成set的一步操作
df.loc[condition,'wen_cha'] = df['bWendu'] - df['yWendu']
df[condition].head()

在这里插入图片描述
如上图所示,在三月份增加了"wen_cha"一列

4.2 解决方法2

如果需要预筛选做后续的处理分析,使用copy复制dataframe。

# 如果需要预筛选做后续的处理分析,使用copy复制dataframe
df_moth3 = df[condition].head()
df_moth3['wen_cha'] = df['bWendu'] - df['yWendu']
df_moth3.head()

在这里插入图片描述
总之,pandas不允许先筛选子dataframe,再进行修改写入。要么使用.loc实现一个步骤直接修改源dataframe;要么先复制一个子dataframe再进行一个步骤执行修改

发布了213 篇原创文章 · 获赞 303 · 访问量 49万+

猜你喜欢

转载自blog.csdn.net/Jiajikang_jjk/article/details/104944599