【问题标题】:Create new column in pandas using if statement使用 if 语句在 pandas 中创建新列
【发布时间】:2020-03-03 12:49:19
【问题描述】:

我正在尝试使用 if 语句在 pandas 中创建一个新列。我有这个df:

df = {'Col1': [7,6,-9],
      'Col2': [0.5,0.5,0.5],
      'Col3': [5,4,3]}

如果Col1 大于0,那么我想将Col2 乘以Col3 以创建新列Col4。如果Col1 不大于0,那么我只想返回0 作为列值。

这是我尝试过的:

df['Col4'] = if df['Col1'] > 0:
    df['Col2'] * df['Col3']
else:
    0  

我收到错误:“SyntaxError:无效语法”

最终的答案应该是这样的:

df = {'Col1': [7,6,-9],
      'Col2': [0.5,0.5,0.5],
      'Col3': [5,4,3],
      'Col4': [2.5,2,0]}

注意因为Col1中的“-9”不大于0,所以Col4应该给0。

【问题讨论】:

    标签: python-3.x pandas


    【解决方案1】:

    您的语法无效。我认为这更接近您想要的:

    import pandas as pd
    
    df = pd.DataFrame({'Col1': [7, 6, -9],
                       'Col2': [0.5, 0.5, 0.5],
                       'Col3': [5, 4, 3]})
    print(df)
    print()
    
    def product(row):
        if row['Col1'] > 0:
            return row['Col2'] * row['Col3']
        else:
            return 0
    
    
    df['Col4'] = df.apply(product, axis=1)
    print(df)
    

    输出:

       Col1  Col2  Col3  Col4
    0     7   0.5     5   2.5
    1     6   0.5     4   2.0
    2    -9   0.5     3   0.0
    

    【讨论】:

    • 先生,您也是英雄
    【解决方案2】:

    我会使用np.where:

    >>> df['Col4'] = np.where(df['Col1'] > 0, df['Col2'] * df['Col3'], 0)                                                   
    >>> df
    Col1  Col2  Col3  Col4
    0     7   0.5     5   2.5
    1     6   0.5     4   2.0
    2    -9   0.5     3   0.0 
    

    基本上wheredf['Col1']大于零,Col4中对应的元素就是df['Col2'] * df['Col3']。否则,它将为零。

    还有一个pd.DataFrame.where,我觉得有点笨拙:

    >>> df['Col4'] = (df['Col2'] * df['Col3']).where(df['Col1'] > 0, 0)
    

    详情可以看this answer

    【讨论】:

    • 你,先生,是个英雄
    猜你喜欢
    • 2019-06-20
    • 1970-01-01
    • 1970-01-01
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-04
    • 2013-10-05
    相关资源
    最近更新 更多