将一列中的特定值复制到基于另一列中的值的整个同一列 - Python\Pandas

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

假设我有以下数据框:

>>> 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.

基于pythonpandas

如何将字符串值从 'Counting_Side' 列复制到所有 'Counting_Side' 列以替换所有 NaN - 所有这些都根据参与者的值(1、2、3 等)。

所以它看起来像这样:

>>> 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

谢谢

使用groupby(...).transform("first")将每个组转换为第一个non-NaN值:

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