【问题标题】:Update dataframe column based with value from either row 1 or row 2 based on condition in python根据 python 中的条件,使用来自第 1 行或第 2 行的值更新数据框列
【发布时间】:2021-02-20 15:23:28
【问题描述】:

我有一个数据框,想根据一个条件创建一个列,该条件用另一列中的一行的值填充该行。

df = pd.DataFrame({'parent':[32, 3, 88, 9, 10, 23, 99, 23],
                   'id':[1, 2, 3, 4, 5, 6, 7, 8],
                   'flag':[True,True,False,True,False,True,True,True]})

我尝试使用 np.where() 来执行此操作,但它不会逐行更新值,而是用满足的条件替换列中的所有值。

df['res'] = np.where(df['flag'] == True, df['parent'], df['id'])

我要创建的数据框如下所示:

df = pd.DataFrame({'parent':[32, 3, 88, 9, 10, 23, 99, 23],
                   'id':[1, 2, 3, 4, 5, 6, 7, 8],
                   'flag':[True,True,False,True,False,True,True,True],
                   'res':[32, 3, 3, 9, 5, 23, 99, 23]})

任何想法我做错了什么?我是 python 新手,非常感谢任何帮助。

【问题讨论】:

  • 您的命令中似乎有错字。将output 更改为df
  • 您的代码有另一个错字。第一段代码中的“标志”属性在第一个位置有一个 False...但在最后一段代码的第一个位置有一个 True。
  • 感谢您指出这些。我做了修复。很抱歉,
  • 另请注意,您可以简单地执行np.where(df['flag'], df['parent'], df['id']) 而无需指定df["flag"]==True

标签: python pandas


【解决方案1】:

正如其他人所指出的,您的代码中有错字。实现所需输出的另一种方法是使用apply 方法:

df['res'] = df.apply(lambda x : x['parent'] if x['flag'] else x['id'], 1)

或者

df['res'] = np.where(df['flag'], df['parent'], df['id'])

输出

   parent  id   flag  res
0      32   1   True   32
1       3   2   True    3
2      88   3  False    3
3       9   4   True    9
4      10   5  False    5
5      23   6   True   23
6      99   7   True   99
7      23   8   True   23

【讨论】:

    【解决方案2】:

    修复您的代码,将输出更改为 df

    df['res1'] = np.where(df['flag'] == True, df['parent'], df['id'])
    df
    Out[176]: 
       parent  id   flag  res  res1
    0      32   1   True   32    32
    1       3   2   True    3     3
    2      88   3  False    3     3
    3       9   4   True    9     9
    4      10   5  False    5     5
    5      23   6   True   23    23
    6      99   7   True   99    99
    7      23   8   True   23    23
    

    【讨论】:

      【解决方案3】:

      只要改变这个:

      df['res'] = np.where(df['flag'] == True, output['parent'], output['id'])
      

      到这里:

      df['res'] = np.where(df['flag'] == True, df['parent'], df['id'])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-06-19
        • 1970-01-01
        • 2021-06-28
        • 1970-01-01
        • 1970-01-01
        • 2015-06-30
        • 1970-01-01
        相关资源
        最近更新 更多