如何使用.loc和.contains设置列值

时间:2019-04-14 22:00:42

标签: python pandas numpy loc

.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'

1 个答案:

答案 0 :(得分:0)

我做了一些调整,并删除了列索引器周围的括号,因为它是单个列。我还注意到代码中的一行也可能是警告的原因,例如建议的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"
相关问题