【问题标题】:A value is trying to be set on a copy of a slice from a DataFrame Warning试图在来自 DataFrame 警告的切片副本上设置值
【发布时间】:2016-12-22 00:12:59
【问题描述】:

不知道为什么我更新到消息建议的 .loc 方法后仍然收到警告?是虚惊一场?

eG.loc[:,'wt']=eG.groupby(['date','BB'])['m'].transform(weightFunction)

试图在数据帧的切片副本上设置值

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  if __name__ == '__main__':

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    我猜你的eG DF 是另一个 DF 的副本...

    这是一个小演示:

    In [69]: df = pd.DataFrame(np.random.randint(0, 5, (10, 3)),  columns=list('abc'))
    
    In [70]: cp = df[df.a > 0]
    
    In [71]: cp.loc[:, 'c'] = cp.groupby('a').b.transform('sum')
    c:\envs\py35\lib\site-packages\pandas\core\indexing.py:549: 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/indexing.html#indexing-view-versus-copy
      self.obj[item_labels[indexer[info_axis]]] = value
    

    解决方法:

    In [72]: cp = df[df.a > 0].copy()
    
    In [73]: cp.loc[:, 'c'] = cp.groupby('a').b.transform('sum')
    

    或者,如果您不需要原始 DF,您可以节省内存:

    In [74]: df = df[df.a > 0]
    
    In [75]: df.loc[:, 'c'] = df.groupby('a').b.transform('sum')
    

    【讨论】:

    • 我想知道如果我们试图获得数据帧的转换版本,为什么我们需要添加 .copy() ?谢谢!
    【解决方案2】:

    这是为了避免所谓的链式索引。 Pandas Chained Index

    正如马克思所建议的,通过使用深拷贝,您可以轻松跳过此警告。

    cp = df[df.a > 0].copy()
    

    或者如果它是一个繁重的数据集并且您不需要原始数据集,只需将切片替换为原始数据集。

    df = df[df.a > 0]
    

    【讨论】:

      猜你喜欢
      • 2016-06-16
      • 2021-03-05
      • 2019-03-30
      • 1970-01-01
      • 2021-08-09
      • 2016-09-23
      • 2016-02-17
      • 2016-08-24
      • 2018-03-25
      相关资源
      最近更新 更多