【问题标题】:SettingWithCopyWarning using .loc [duplicate]SettingWithCopyWarning 使用 .loc [重复]
【发布时间】:2020-03-28 01:16:02
【问题描述】:

我有一个数据框,其中包含不同日期和日期的不同植物的数据。

我创建了只包含我想要使用的植物的新数据框:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

%matplotlib inline

df_plants = pd.read_csv('Data_plants_26_11_2019.csv')
df_Nit=pd.read_csv('chemometrics.csv')

#create new colum which contains aonly the hour using lambda
df_plants['Hour']=df_plants['time'].apply(lambda time: time.split(' ')[1])
df_plants['date']=df_plants['time'].apply(lambda time: time.split(' ')[0])

#select only my plants
options=['J01B','J01C','J02C','J02D','J03B','J03C','J04C','J08C','J08D','J09A','J09C','J10A','J12C','J12D','J13A','J14A','J15A','J18A']
filter_plants=df_plants[df_plants['plant'].isin(options)]

创建后,我尝试计算一些索引(使用图像中未显示的列),但我开始收到在所有植物上计算时没有得到的警告:

filter_plants['NDVI']=(filter_plants['801.03']- filter_plants['680.75'])/(filter_plants['801.03']+filter_plants['680.75'])

C:\ProgramData\Anaconda2\lib\site-packages\ipykernel_launcher.py:1: SettingWithCopyWarning:试图在一个副本上设置一个值 从 DataFrame 切片。尝试使用 .loc[row_indexer,col_indexer] = 取而代之的价值

请参阅文档中的注意事项: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy """启动 IPython 内核的入口点。

我在这里https://www.dataquest.io/blog/settingwithcopywarning/ 读到了这个警告,我认为这与我没有用 loc 创建“过滤器植物”的事实有关,所以我之前尝试过添加它:

#select only plants that their nitrogen content was checked
options=['J01B','J01C','J02C','J02D','J03B','J03C','J04C','J08C','J08D','J09A','J09C','J10A','J12C','J12D','J13A','J14A','J15A','J18A']
filter_plants=df_plants.loc[df_plants['plant'].isin(options)]

但它没有帮助而且是一样的。 我也尝试在索引计算中添加 loc,但仍然遇到同样的错误。

有什么问题?我该如何修复它,这样我在接下来运行的步骤中就不会出错?

我的最终目标是摆脱警告。

【问题讨论】:

    标签: python pandas chaining


    【解决方案1】:

    我通常处理此警告的方式是df.copy()。基本上这里的问题是熊猫没有正确地将filter_plants 制作为自己的数据框(如果我理解正确的话),而只是df_plants 的一部分,除非您使用.copy()

    如果您只是将您的线路更改为:

    filter_plants=df_plants[df_plants['plant'].isin(options)].copy()
    

    这应该可以解决它。

    【讨论】:

      猜你喜欢
      • 2014-07-04
      • 1970-01-01
      • 2014-10-18
      • 2016-04-09
      • 2018-09-11
      • 2021-11-30
      相关资源
      最近更新 更多