【问题标题】:Pandas If Statements (excel equivalent)Pandas If 语句(相当于 excel)
【发布时间】:2015-09-07 15:00:27
【问题描述】:

我正在尝试在 Pandas 中创建一个简单的 if 语句。

excel版本如下:

=IF(E2="ABC",C2,E2)

我不知道如何根据字符串或部分字符串来分配它。

这就是我所拥有的。

df['New Value'] = df['E'].map(lambda x: df['C'] if x == 'ABC' else df['E']]

我知道我在这里犯了一个错误。

结果是每个单元格中的整个数据框值。

任何帮助将不胜感激!

【问题讨论】:

    标签: python-3.x if-statement pandas


    【解决方案1】:

    使用np.where:

    In [36]:
    df = pd.DataFrame({'A':np.random.randn(5), 'B':0, 'C':np.arange(5),'D':1, 'E':['asdsa','ABC','DEF','ABC','DAS']})
    df
    
    Out[36]:
              A  B  C  D      E
    0  0.831728  0  0  1  asdsa
    1  0.734007  0  1  1    ABC
    2 -1.032752  0  2  1    DEF
    3  1.414198  0  3  1    ABC
    4  1.042621  0  4  1    DAS
    
    In [37]:    
    df['New Value'] = np.where(df['E'] == 'ABC', df['C'], df['E'])
    df
    
    Out[37]:
              A  B  C  D      E New Value
    0  0.831728  0  0  1  asdsa     asdsa
    1  0.734007  0  1  1    ABC         1
    2 -1.032752  0  2  1    DEF       DEF
    3  1.414198  0  3  1    ABC         3
    4  1.042621  0  4  1    DAS       DAS
    

    np.where 的语法是:

    np.where( < condition >, True condition, False condition )
    

    因此,当条件为 True 时,它返回 True 条件,而当 False 另一个条件时。

    【讨论】:

    • 对不起,只是添加到这个。如何在字符串中获取 or 函数?例如。 “ABC”还是“CBA”?
    • 如果您有新问题,请提出新问题,除非是非常小的问题
    • 按位使用| 运算符:np.where((df['E'] == 'ABC') | (df['E'] == 'CBA), df['C'], df['E'])
    猜你喜欢
    • 1970-01-01
    • 2019-03-10
    • 1970-01-01
    • 2013-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 2019-05-29
    相关资源
    最近更新 更多