首页 > 解决方案 > 在查询返回的索引处更新数据框

问题描述

我想让查询返回一个视图,以便我可以修改字段而不会产生此错误。

SettingWithCopyWarning:试图在 DataFrame 中的切片副本上设置值。尝试改用 .loc[row_indexer,col_indexer] = value

请参阅文档中的注意事项:http: //pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

我有一个q在这里缩写的多行(长)查询:

df1 = pd.Dataframe(...)
q = "tcpstream==1  and ipsrc=='10.0.0.1' and sport==5201"
df = df1.query(q)    
df['dest'] = "toto"   # <--- this generates the warning/error

显然我可以做一个 df1.update(df) 但这似乎是一种浪费,我正在寻找更有效的东西。

标签: pythonpandasdataframe

解决方案


pd.DataFrame.query设计用于查询,而不是设置值。如果您想使用字符串查询作为掩码,您可以计算索引并输入pd.DataFrame.loc

df.loc[df.query(q).index, 'dest'] = 'toto'

推荐阅读