Python 基于多个条件和列创建新列
我想使用几个条件和columsn为一个大表创建一个新列,但我不确定最好的方法 数据帧{'a':['a',B,B,C,D], “b':[y','n','y','n',np.nan],“c':[10,20,10,40,30],“d':[3,1,4,2,1]} 测向头 def fundf=df: df=df.copy 如果df.a=='a'&df.b=='n': df['new_Col']=df.c+df.d 如果df.a=='a'&df.b=='y': df['new_Col']=df.d*2 其他: df['new_Col']=0 返回df 享乐 或 def fundf=df: df=df.copy 如果df.a=='a'&df.b=='n': 返回=df.c+df.d 如果df.a=='a'&df.b=='y': 返回df.d*2 其他: 返回0 df['new_Col]df.applyfun 或者使用np.where: df['new_Col']=np.wheredf.a=='a',df.b=='n',df.c+df.d,0 df['new_Col']=np.wheredf.a=='a',df.b=='y',df.d*2,0 看来你需要 这是一种算术方法,我在示例中为案例a='a'和b='n'添加了一行: 样品Python 基于多个条件和列创建新列,python,python-3.x,pandas,Python,Python 3.x,Pandas,我想使用几个条件和columsn为一个大表创建一个新列,但我不确定最好的方法 数据帧{'a':['a',B,B,C,D], “b':[y','n','y','n',np.nan],“c':[10,20,10,40,30],“d':[3,1,4,2,1]} 测向头 def fundf=df: df=df.copy 如果df.a=='a'&df.b=='n': df['new_Col']=df.c+df.d 如果df.a=='a'&df.b=='y': df['new_Col']=df.d*2 其他
Out[1369]:
a b c d
0 A y 10 0.3
1 B n 20 0.1
2 B y 10 0.4
3 C n 40 0.2
4 D NaN 30 0.1
5 A n 50 0.9
nc = df.a.eq('A') & df.b.eq('y')
mc = df.a.eq('A') & df.b.eq('n')
nr = df.d * 2
mr = df.c + df.d
df['new_col'] = nc*nr + mc*mr
Out[1371]:
a b c d new_col
0 A y 10 0.3 0.6
1 B n 20 0.1 0.0
2 B y 10 0.4 0.0
3 C n 40 0.2 0.0
4 D NaN 30 0.1 0.0
5 A n 50 0.9 50.9
Out[1369]:
a b c d
0 A y 10 0.3
1 B n 20 0.1
2 B y 10 0.4
3 C n 40 0.2
4 D NaN 30 0.1
5 A n 50 0.9
nc = df.a.eq('A') & df.b.eq('y')
mc = df.a.eq('A') & df.b.eq('n')
nr = df.d * 2
mr = df.c + df.d
df['new_col'] = nc*nr + mc*mr
Out[1371]:
a b c d new_col
0 A y 10 0.3 0.6
1 B n 20 0.1 0.0
2 B y 10 0.4 0.0
3 C n 40 0.2 0.0
4 D NaN 30 0.1 0.0
5 A n 50 0.9 50.9