I have the following DataFrame with two columns and I would like to create a new column based on this condition :
- if the value of y is -1 take the value of x
- if the value of x is -1 take the value of y
df = pd.DataFrame({'x': ['day', 'day', 'night', '-1', '-1', '-1'],
'y': ['-1', '-1', '-1', 'night', 'day', 'day']})
df
I have tried the following but I got a None and NaN output
def func(x):
if (x['y'] == -1):
return x['x']
elif (x['x'] == -1):
return x['y']
df = df.assign(z=df.apply(func, axis=1))
df
and
conditions = [
(df['y'] == -1),
(df['x'] == -1),
]
choices = [df['x'],df['y']]
df['z1'] = np.select(conditions, choices, default=np.nan)
df
the expected result should be like this
df = pd.DataFrame({'x': ['day', 'day', 'night', '-1', '-1', '-1'],
'y': ['-1', '-1', '-1', 'night', 'day', 'day'],
'z':['day','day','night','night','day','day']})
df