【发布时间】:2019-09-04 22:01:34
【问题描述】:
.loc 和 .contains 函数都返回一个数据框对象。 pandas 文档指出,要为列中的每一行重新分配一个值,我应该使用 .loc,但是当与 .contains 结合使用时,我会收到以下警告:
试图在 DataFrame 的切片副本上设置一个值。 尝试改用 .loc[row_indexer,col_indexer] = value 请参阅文档中的注意事项:http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
但是,该过程有效,并且我为数据框列中的每一行重新分配了所需的值。如何避免此警告?
#works
df.loc[df["matchType"]=='duo',["matchType"]]='duo'
#warning thrown but still works
df.loc[df["matchType"].str.contains('duo'),["matchType"]]='duo'
【问题讨论】:
-
我无法重现该问题。当我运行它们时,这两个赋值语句都不会产生任何警告(使用 pandas 版本 0.24.2)。
-
This 链接会有所帮助。引发
SettingWithCopyWarning的最终原因可能是较早的代码行;单独这个 sn-p 应该没有问题。
标签: python pandas numpy pandas-loc