【发布时间】:2016-01-05 19:37:35
【问题描述】:
我正在尝试从一组行中修改一组列,当然我会收到以下警告:
A value is trying to be set on a copy of a slice from a DataFrame
我看到了一个类似的问题here,但我无法理解它。
所以如果我们按照这个示例代码:
from random import random as rd
ex= pd.DataFrame([{"group": ["a","b"][int(round(rd()))], "colA": rd()*10, "colB": rd()*10, "colC": rd()*10, "colD": rd()*10} for _ in range(20)])
cols = [col for col in ex.columns if col != "group"]
我只想修改属于 group a 的行和列 cols 上的行,对此我有点直觉地尝试(并收到警告警告):
ex[ex["group"]=="a"][cols] = ex[ex["group"]=="a"][cols]/ex.ix[0,cols]
列数匹配并且具有相同的标签,所以我想知道是否必须像这样一一进行:
for idx in ex[ex["group"]=="a"].index:
for col in cols:
ex.ix[idx, col]=ex.ix[idx, col]/ex.ix[0,col]
这当然可行,但感觉像是退后一步。那么做这样的事情的正确方法是什么?
【问题讨论】: