我有代码行
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语法时遇到的问题。任何有关如何更正此语法的建议都将受到赞赏。
您很可能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()
而且没有警告显示。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句