【问题标题】:Change row to 0 based on conditions [duplicate]根据条件将行更改为 0 [重复]
【发布时间】:2021-06-11 12:43:29
【问题描述】:

我有一个数据框:

   1     0      1         2
   2     2      3         1
   3     8      2         9 

预期输出:

       1     0      1         0
       2     2      3         0
       3     8      2         9 
    

我最初的想法是

     df = np.where(df['Reported'] >= df['Goal'], df['Score'] = 0, df['Score'] 

这没有按需要工作。

【问题讨论】:

    标签: python pandas numpy


    【解决方案1】:

    您已经接近了,只需将 df['Score'] = 0 替换为 0 即可通过条件并将输出分配给 df.Score col。

    df.Score = np.where(df['Reported'] >= df['Goal'],0, df['Score'] )
    

    输出

        ID  Goal    Reported    Score
    0   1   0       1           0
    1   2   2       3           0
    2   3   8       2           9
    

    【讨论】:

      【解决方案2】:

      您可以使用loc 方法进行索引:

      df.loc[df['Reported'] >= df['Goal'],'Score'] = 0
      

      【讨论】:

        猜你喜欢
        • 2019-04-13
        • 1970-01-01
        • 1970-01-01
        • 2022-01-14
        • 2013-08-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多