Hello,
I want to assign a value in "Value" column into a new column and up to all next empty rows until next value comes. My expected value is available in a new column 'Expected_Value'.
I tried this using two functions (apply lambda & assign lambda), however, there were error messages as follows.
apply lambda method
Assign lambda method
Appreciate it if someone could help with this.
I want to assign a value in "Value" column into a new column and up to all next empty rows until next value comes. My expected value is available in a new column 'Expected_Value'.
1 2 3 4 5 6 |
import pandas as pd df2 = pd.DataFrame({ 'Value' :[ 'Second' , np.nan, np.nan, 'Fourth' , np.nan], 'Name' :[ 'John' , 'Tom' , 'Tom' , 'Tom' , 'One' ], 'Expected_Value' :[ 'Second' , 'Second' , 'Second' , 'Fourth' , 'Fourth' ] }) |
I tried this using two functions (apply lambda & assign lambda), however, there were error messages as follows.
apply lambda method
1 2 3 4 5 |
df2[ 'new_value' ] = np.nan df2[ 'new_value' ] = df2. apply ( lambda row: row[ 'Value' ] if (~pd.isna(row[ 'Value' ])) else row[ 'new_value' ].shift( - 1 )) # KeyError: 'Value' |
1 2 3 |
del df2[ 'new_value' ] df2 = df2.assign(new_value = lambda x: (x[ 'Value' ]) if (~(x[ 'Value' ].isna())) else x[ 'new_value' ].shift( - 1 )) # ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() |