Skip to main content
 首页 » 编程设计

python之从 4 个指定列中只获取两个值并将有效值合并到 2 列中

2025年05月04日23三少

df:

index      a          b          c           d 
- 
0          1          2          NaN         NaN 
1          2          NaN        3           NaN 
2          5          NaN        6           NaN 
3          1          NaN        NaN         5 

df 期望:

index      one        two 
- 
0          1          2          
1          2          3      
2          5          6         
3          1          5 

上面的输出示例是不言自明的。基本上,我只需要将 [a, b, c, d] 列中的两个值(NaN 除外)转移到另一组两列 ["one", "two"]

请您参考如下方法:

使用回填缺失值并选择前 2 列:

df = df.bfill(axis=1).iloc[:, :2].astype(int) 
df.columns = ["one", "two"] 
print (df) 
       one  two 
index           
0        1    2 
1        2    3 
2        5    6 
3        1    5