.loc访问器无法修复熊猫“ SettingWithCopyWarning”

时间:2018-11-05 13:53:12

标签: python pandas

我有一个带有DateTimeIndex的DataFrame,我该如何将带有Index日历周的附加列添加到DataFrame。 我当前的方法是以下代码,它可以按预期工作:

output_df['week_number'] = output_df.index.week

但是我收到以下警告:

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

我已经尝试通过更改为

来修复它
output_df['week_number'] = output_df.index.week.copy()

但它没有任何改变。

进一步遵循建议并更改为.loc-accessor:

output_df.loc[:,'week_number'] = output_df.index.week

导致另一个警告:

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)

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

避免此警告的正确方法是什么?谢谢您的帮助。

0 个答案:

没有答案