【问题标题】:settingWithCopyWarning pandas setting via indexsettingWithCopyWarning 通过索引设置熊猫
【发布时间】:2017-05-07 08:05:10
【问题描述】:

我正在尝试通过索引选择来设置数据框中列的值。

myindex = (df['city']==old_name) & (df['dt'] >= startDate) & (df['dt'] < endDate)
new_name = 'Boston2
df['proxyCity'].ix[myindex ] = new_name

在上面,给定myindex中的条件,我想在proxyCity列中分配值Boston2

C:\Users\blah\Anaconda3\lib\site-packages\pandas\core\indexing.py:132: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  self._setitem_with_indexer(indexer, value)

在不引入文档中概述的问题的情况下,做我想做的事情的正确方法是什么。

此链接using pandas to select rows conditional on multiple equivalencies 中的答案似乎是按照我实现它的方式进行的。

我不确定这样做的正确方法是什么。

【问题讨论】:

    标签: python pandas indexing


    【解决方案1】:

    为避免双重索引,请更改

    df['proxyCity'].ix[myindex ] = new_name
    

    df.loc[myindex, 'proxyCity'] = new_name
    

    它更高效(更少的__getitem__ 函数调用)并且在大多数情况下,将消除SettingWithCopyWarning

    但是请注意,如果 df 是另一个 DataFrame 的子 DataFrame,则可能会发出 SettingWithCopyWarning 即使使用df.loc[...] = new_name。在这里,Pandas 警告修改 df 不会影响其他 DataFrame。 如果这不是您的意图,那么可以安全地忽略 SettingWithCopyWarning。有关使SettingWithCopyWarning 静音的方法,请参阅this post

    【讨论】:

      【解决方案2】:

      您可以使用mask

      mask = (df.city == old_name) & (df.dt >= startDate) & (df.dt < endDate)
      new_name = 'Boston2
      df.loc[:, 'proxyCity'] = df.proxyCity.mask(mask, new_name)
      # Or
      df.proxyCity.mask(mask, new_name, inplace=True)
      

      【讨论】:

        猜你喜欢
        • 2015-02-23
        • 1970-01-01
        • 1970-01-01
        • 2014-05-25
        • 2017-12-23
        • 1970-01-01
        • 2016-11-03
        相关资源
        最近更新 更多