【问题标题】:Pandas group by then apply throwing a warning熊猫组然后申请抛出警告
【发布时间】:2019-05-14 19:20:46
【问题描述】:

我有代码行

df = df.groupby(by=['col_A','col_B'])['float_col_c']
df.loc[:,'amount_cumulative'] = df.apply(lambda x: x.cumsum())

哪个会引发警告:

/anaconda3/lib/python3.6/site-packages/pandas/core/indexing.py:362: 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[key] = _infer_fill_value(value)
/anaconda3/lib/python3.6/site-packages/pandas/core/indexing.py:543: 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] = s

通常,当我看到该错误时,我可以将某些内容更改为.loc[] 来修复它,但在这种情况下,警告似乎是指另一个问题。我知道我可以压制警告,但我宁愿理解我在使用 Pandas 语法时遇到的问题。非常感谢任何有关如何更正此语法的建议。

【问题讨论】:

    标签: python pandas warnings


    【解决方案1】:

    您的df 很可能已经是另一个数据帧的副本。你的命名df_rev_melt_trim 也暗示了这一点。测试

    old_df = pd.DataFrame({'A':np.random.randint(1,10,1000),
                       'B':np.random.randint(1,10,1000),
                       'C':np.random.uniform(0,1,1000)})
    
    df = old_df[old_df['A'] > 5]
    
    df['amount_cumulative'] = df.groupby(by=['A','B'])['C'].cumsum()
    

    产生相同的警告。相反,您可以这样做:

    old_df.loc[df.index,'amount_cumulative'] = df.groupby(by=['A','B'])['C'].cumsum()
    

    没有警告显示。

    【讨论】:

      【解决方案2】:

      我相信这是因为.loc[:, 'amount_cumulative'] 索引,它返回df 的一部分,而不是对新列的引用

      更新:df 本身就是一个副本,正如@QuangHoang 正确指出的那样,在这种情况下,以下内容仍会引发错误。

      您可以通过以下简单的方法获得预期结果而不会发出警告:

      df['amount_cumulative'] = df.groupby(['col_A','col_B'])['float_col_c'].cumsum()
      

      【讨论】:

      • 这缩短了警告但它仍然抛出: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 df_rev_melt_trim['amount_cumulative'] = df_rev_melt_trim.groupby(by=['company_id','revenue_type'])['amount_usd'].cumsum()
      猜你喜欢
      • 2019-01-23
      • 1970-01-01
      • 1970-01-01
      • 2017-11-09
      • 2017-11-08
      • 2020-12-01
      • 1970-01-01
      • 2022-01-26
      • 2018-11-24
      相关资源
      最近更新 更多