我正在尝试有条件地更新我的熊猫数据框中的多行。这是我的数据:
df = pd.DataFrame([[1,1,1], [2,2,2], [3,3,3]], columns=list('ABC'))
我可以通过两个步骤完成我想要的更新:
df.loc[df['A'] == 1, 'B'] = df['C'] +10
df.loc[df['A'] == 1, 'A'] = df['C'] +11
或者我可以一步更新为常数值:
df.loc[df['A'] == 1, ['A', 'B']] = [11, 12]
但我无法在一个步骤中更新其他列中的多个列:
df.loc[df['A'] == 1, ['A', 'B']] = [df['C'] + 10, df['C'] + 11]
...
ValueError: shape mismatch: value array of shape (2,3) could not be broadcast to indexing result of shape (1,2)
我有什么想法可以做到这一点吗?
编辑:感谢@EdChum针对简单案例的简单解决方案 - 更新了问题以展示更复杂的现实。
答案 0 :(得分:5)
所以在几年后查看这个问题我看到了错误,强制返回结果,因此它正确分配你需要访问标量值并使用这些来分配所以它们按照需要对齐:
In [22]:
df.loc[df['A'] == 1, ['A', 'B']] = df['C'].values[0] + 10,df['C'].values[0] + 11
df
Out[22]:
A B C
0 11 12 1
1 2 2 2
2 3 3 3
答案 1 :(得分:1)
I'm nor sure whether it's the best way to achieve that, but it works:
In [284]: df.loc[df['A'] == 1, ['A', 'B']] = pd.DataFrame({'A':df.C + 10, 'B':df.C + 11}, index=df.index)
In [285]: df
Out[285]:
A B C
0 11 12 1
1 2 2 2
2 3 3 3