Need help when working with the Pandas DataFrame object.

Task:

There is a data set, it is necessary for objects, where the value in the column = 1 , replace in the other column the same row with NaN by -1 .

Explanation

heduc column - the duration of education by the husband (if the husband is not NaN , must be replaced by -1 ) the column newermarr - whether the person is married (if 1 not newermarr ) is necessary for everyone outside the marriage, the period of education for the husband is -1 .

Here is an attempt to solve, I can not understand how to leave existing values ​​in else

 data_woman['heduc'] = data_woman['nevermarr'].apply(lambda x : -1 if x == 1 else x) 
  • heduc column - the duration of education by the husband (if the husband is not NaN, must be replaced by -1) the column newermarr - whether the person is married (if 1 is not included) is necessary for everyone outside the marriage, the period of education for the husband is -1. Here is an attempt to solve, I can’t understand how to leave the existing data_woman ['heduc'] = data_woman ['nevermarr'] else in. apply (lambda x: -1 if x == 1 else x) - Dmitry Astapenko
  • Can you give an example of input data (2-3 lines) in the question and what do you want to get at the output? - MaxU

1 answer 1

Example:

 In [35]: df Out[35]: heduc nevermarr 0 5.0 1 1 NaN 1 2 3.0 0 3 NaN 0 In [36]: df.loc[df['nevermarr']==1, 'heduc'] = df.loc[df['nevermarr']==1, 'heduc'].fillna(-1) In [37]: df Out[37]: heduc nevermarr 0 5.0 1 1 -1.0 1 2 3.0 0 3 NaN 0