【问题标题】:python: if column condition met change value in that column [duplicate]python:如果列条件满足该列中的更改值[重复]
【发布时间】:2019-07-05 04:43:11
【问题描述】:

如果 col2 的值为 0,我如何将 10 添加到列 col2 中的任何值。较大数据框的一般情况。

     col1 col2
row1    1   2
row2    3   0

所以我得到:

     col1 col2
row1    1   2
row2    3   10

这让我找到了正确的行:

df2.loc[lambda df2: df2['col2'] == 0 ] 

这会做整行,我不想要:

df2.loc[df2['col2'] == 0 ] = 10

【问题讨论】:

  • df.replace(0, 10)?

标签: python python-3.x


【解决方案1】:

使用np.where()

import numpy as np

df['col2'] = np.where(df['col2']==0, 10, df['col2'])

【讨论】:

    猜你喜欢
    • 2021-05-19
    • 2021-06-10
    • 1970-01-01
    • 2019-08-01
    • 2018-12-13
    • 2021-06-26
    • 2014-02-11
    • 1970-01-01
    • 2019-10-12
    相关资源
    最近更新 更多