大 pandas 如果声明(相当于excel) [英] Pandas If Statements (excel equivalent)

查看:155
本文介绍了大 pandas 如果声明(相当于excel)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to create a simple if statement in Pandas.

excel版本如下:

The excel version is as follows:

= IF(E2 =ABC,C2,E2)

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

我坚持如何基于字符串或部分字符串来分配它。

I'm stuck on how to assign it based on a string or partial string.

这就是我所拥有的。

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

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

I know I'm making a mistake here.

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

As the outcome is the entire dataframe values in each cell.

非常感谢任何帮助!

推荐答案

使用 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 时返回另一个条件。

So when the condition is True it returns the True condition and when False the other condition.

这篇关于大 pandas 如果声明(相当于excel)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆