代码之家  ›  专栏  ›  技术社区  ›  Melvin

基于Pandas中带条件的行的新列

  •  1
  • Melvin  · 技术社区  · 8 年前

    给定以下数据帧,用下面描述的列定义

    original_df = [o1, o2, o3, o4]
    weights_df = [w1, w2, w3, w4]
    conditions_df = [c1, c2, c3, c4]
    

    我需要在上面建一个新专栏 原始_df 基于 o1/w1 但这取决于 c1 ,取值[“+”或“-”,我需要做 -o1/w1

    只要我这么做了:

    orignal_df['newcolumn'] = original_df / weights_df
    

    当然,我划分了这两个项,但没有应用条件,我尝试使用map和apply函数,但我不确定如何将第三列添加到函数中。

    2 回复  |  直到 8 年前
        1
  •  1
  •   lisa    8 年前
    original_df = [100, 200, 300, 400]
    weights_df = [10, 20, 30, 40]
    conditions_df = [1, 2, 3, 4]
    
    df = pd.DataFrame({'x':original_df, 'y':weights_df, 'z':conditions_df})
    def div(x, y, z):
        if z > 2:
            return float(x/y)
        else:
            return float(-1*x/y)
    
    df['new_feature'] = df.apply(lambda p: div(p['x'], p['y'], p['z']), axis=1)
    

    这是解决问题的一种方法。如果您的条件_df包含“+”/“-”,则可以在中更改条件 def div(x, y, z) 照着

        2
  •  0
  •   jezrael    8 年前

    您可以使用 numpy.where 对于条件掩码:

    #data from lisa answer
    #df = pd.DataFrame({'x':original_df, 'y':weights_df, 'z':conditions_df})
    
    df['new_feature'] = df['x'] / df['y'] *  np.where(df['z'] > 2, 1, -1)
    print (df)
         x   y  z  new_feature
    0  100  10  1        -10.0
    1  200  20  2        -10.0
    2  300  30  3         10.0
    3  400  40  4         10.0
    

    时间安排 :

    #4k rows
    df = pd.concat([df]*1000).reset_index(drop=True)
    
    #lisa answer
    In [95]: %timeit df['new_feature1'] = df.apply(lambda p: div(p['x'], p['y'], p['z']), axis=1)
    10 loops, best of 3: 123 ms per loop
    
    In [96]: %timeit df['new_feature2'] = df['x'] / df['y'] *  np.where(df['z'] > 2, 1, -1)
    1000 loops, best of 3: 595 µs per loop