python - 如何有条件地更新 Pandas 数据框中的多列

标签 python pandas dataframe

我正在尝试有条件地更新我的 Pandas 数据框中的多行。这是我的数据:

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 为简单案例提供的简单解决方案 - 已更新问题以展示更复杂的现实。

最佳答案

所以几年后看这个问题我看到了错误,要强制返回结果以便正确分配,您需要访问标量值并使用这些值进行分配,以便它们按需要对齐:

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

关于python - 如何有条件地更新 Pandas 数据框中的多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37675869/

相关文章:

python - Django 休息框架 : Embed Viewset Inside Viewset

python - 使用身份验证从 https 下载文件

python - 在 Tensorflow 2.2.0 中,我的 model.history.history 在拟合数据和 validation_data 后为空

python - 值错误 : Wrong number of items passed - Meaning and suggestions?

python - 添加一个新的 pandas 列,其中包含字典中的映射值

python - 如何将非对称成对距离矩阵转换为字典?

python - Opencv Python人脸检测

python - 如何从文件类型获取文件扩展名?

r - 如何在R中进行组匹配?

python - 属性错误: 'str' object has no attribute 'to_datetime'