mercredi 30 mai 2018

Creating a new column with ifelse condition (python)

I am trying to create a new column 'New' that:

1) if 'y' values is different from zero, give me 'y'

2) if 'y' is equal zero, give me 'yhat' value

           ds     y         ds       yhat
0    1999-03-05  45.0 1999-03-05  37.168417
1    1999-03-06  45.0 1999-03-06  37.109215
2    1999-03-07  45.0 1999-03-07  37.049726
3    1999-03-08  45.0 1999-03-08  36.987036
4    1999-03-09  45.0 1999-03-09  36.926852
5    1999-03-10  45.0 1999-03-10  36.864715
6    1999-03-11  45.0 1999-03-11  36.771622
7    1999-03-12  45.0 1999-03-12  36.712117
8    1999-03-13  45.0 1999-03-13  36.646144
9    1999-03-14  45.0 1999-03-14  36.578244
...         ...   ...        ...        ...
7356        NaT   0   2019-04-25   8.321119
7357        NaT   0   2019-04-26   8.315796

In order to do that, I am using this function:

df['New'] = np.where(df['y']!=0, df['y'], df['yhat'])

But I get an error saying:

KeyError: 'y'

Aucun commentaire:

Enregistrer un commentaire