Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何基于其他两列有条件地创建一个新列_Python_Pandas - Fatal编程技术网

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)