熊猫添加带有 if 条件的列

Tyl*_*rNG 1 python pandas

嗨,我不确定如何将新列 z 添加到我现有的 df 中,其中 z = x if x is not 0 else y 。

例如:

Name  x  y  |z (new col)
A     1  5  |1
B     2  6  |2
C     0  3  |3
D     0  0  |0
Run Code Online (Sandbox Code Playgroud)

np.where 在这种情况下适用吗?

谢谢!

Luc*_*esl 5

你可以试试:

 df['z'] = np.where(df['x']!=0,df['x'],df['y'])
Run Code Online (Sandbox Code Playgroud)