【问题标题】:How to set column values using .loc and .contains如何使用 .loc 和 .contains 设置列值
【发布时间】: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


【解决方案1】:

我做了一些调整并删除了列索引器周围的括号,因为它是单列。我还注意到我的代码中的一行也可能导致警告,就像 gmds 建议的那样,我简化了一些事情:

df.loc[(df['matchType'].str.contains('solo')==False) & 
(df['matchType'].str.contains('duo')==False),"matchType"]="other"
-->
df.loc[df['matchType'].str.contains('solo|duo')==False),"matchType"]="other"

【讨论】:

    猜你喜欢
    • 2019-04-12
    • 2023-04-03
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    • 2019-12-16
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    相关资源
    最近更新 更多