pandas – Python: create a new column from existing columns
pandas – Python: create a new column from existing columns
You can use apply
with option axis=1
. Then your solution is pretty concise.
df[z] = df.apply(lambda row: row.y if pd.notnull(row.y) else row.x, axis=1)
The new column z
get its values from column y
using df[z] = df[y]
. This brings over the missing values so fill them in using fillna
using column x
. Chain these two actions:
>>> df[z] = df[y].fillna(df[x])
>>> df
x y z
0 1 NaN 1
1 2 8 8
2 4 10 10
3 8 NaN 8
pandas – Python: create a new column from existing columns
Use np.where
:
In [3]:
df[z] = np.where(df[y].isnull(), df[x], df[y])
df
Out[3]:
x y z
0 1 NaN 1
1 2 8 8
2 4 10 10
3 8 NaN 8
Here it uses the boolean condition and if true returns df[x]
else df[y]