Search code examples
pythonpandascopypandas-groupby

Copy a specific value in a column, to the entire same column based on a value in another column - Python\Pandas


Assuming I have the following dataframe:

>>> df

particpant  Counting_Side  
1           NaN            
1           NaN        
1           Left_To_Right
2           NaN         
2           NaN           
2           NaN    
2           NaN            
2           NaN        
2           Right_To_Left
3           NaN         
3           NaN           
3           Left_To_Right
4           NaN
4           Right_To_Left

etc.

Based on python pandas

How do I copy the string value from column 'Counting_Side' to all the 'Counting_Side' column replacing all the NaN's - all that according to the particpant's value (1, 2, 3 etc).

so it will look like this:

>>> df
particpant  Counting_Side  
1           Left_To_Right            
1           Left_To_Right        
1           Left_To_Right
2           Right_To_Left         
2           Right_To_Left           
2           Right_To_Left    
2           Right_To_Left            
2           Right_To_Left        
2           Right_To_Left
3           Left_To_Right         
3           Left_To_Right           
3           Left_To_Right
4           Right_To_Left
4           Right_To_Left

Thanks


Solution

  • Use groupby(...).transform("first") to transform every group to the first non-NaN value:

    df["particpant"] = df.groupby("particpant")["Counting_Side"].transform("first")