Python 如何基于其他两列有条件地创建一个新列
我有一个数据框,看起来像这样:Python 如何基于其他两列有条件地创建一个新列,python,pandas,Python,Pandas,我有一个数据框,看起来像这样: col 1 | col2 | col3 | col4 | col5 'abc' | 1 | 20 | 10 | 15 'abc' | 2 | 25 | 5 | 30 'def' | 1 | 340 | 12 | 22 'def' | 2 | 185 | 16 | 120 ... 我想创建另一列col6,它基于条件:如果col2==1,那么col3*col5,否则为0;如果col2==2,则col4*c
col 1 | col2 | col3 | col4 | col5
'abc' | 1 | 20 | 10 | 15
'abc' | 2 | 25 | 5 | 30
'def' | 1 | 340 | 12 | 22
'def' | 2 | 185 | 16 | 120
...
我想创建另一列col6
,它基于条件:如果col2
==1,那么col3
*col5
,否则为0;如果col2
==2,则col4
*col5
,否则为0。因此,生成的df应该如下所示:
col 1 | col2 | col3 | col4 | col5 | col6
'abc' | 1 | 20 | 10 | 15 | 300
'abc' | 2 | 25 | 5 | 30 | 150
'def' | 1 | 340 | 12 | 22 | 7480
'def' | 2 | 185 | 16 | 120 | 1920
...
如果1或2都不是,它应该返回0的原因只是为了防止col2
没有1或2。使用:
试试这个
df.loc[df['col2'] ==1,'col6']=df['col3']*df['col5']
df.loc[df['col2'] ==2,'col6']=df['col4']*df['col5']
df['col6']=df['col6'].fillna(0)
我尝试过这个,但是它为所有的
col6
恢复了0.0
。我取出了default=0
,但仍然得到了0@jceg316-数据是数字的吗?什么返回值df.col2.dtype
?dtype('int64')
@jceg316-这里不是0的倍数?例如,在col5的实数据中?所有列中都是实数据,没有零和col3
col4
col5
都是浮点数
df.loc[df['col2'] ==1,'col6']=df['col3']*df['col5']
df.loc[df['col2'] ==2,'col6']=df['col4']*df['col5']
df['col6']=df['col6'].fillna(0)