python - 在查询返回的索引处更新数据框
问题描述
我想让查询返回一个视图,以便我可以修改字段而不会产生此错误。
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) 但这似乎是一种浪费,我正在寻找更有效的东西。
解决方案
pd.DataFrame.query
设计用于查询,而不是设置值。如果您想使用字符串查询作为掩码,您可以计算索引并输入pd.DataFrame.loc
:
df.loc[df.query(q).index, 'dest'] = 'toto'
推荐阅读
- angular - 如何处理 Firebase 错误“后端未在 10 秒内响应”
- angular - 尝试将数据注入 mat-dialog 时出错
- couchdb - 更新设计文档时,CouchDB 是否会无条件地重建索引?
- python - 正则表达式:提取 [..] 之间的字符串
- node.js - 当一组用户完成一项任务时,如何执行一项任务?这可以使用 nodejs 和 mongodb 来完成吗?
- python - alembic.util.exc.CommandError:找不到由“f1942fde9843”标识的修订版
- python - 为什么scrapy 说我正在迭代一个“itemMeta”对象?
- r - R中的共现矩阵,对变量的值求和以填充单元格
- regex - ingress rewrite-target 中编号占位符的含义是什么?
- c# - 编写 ASP.NET 自定义存储提供程序