Skip to main content
 首页 » 编程设计

python之Pandas:从其他 Dataframe 中的某些列创建新 Dataframe

2025年05月04日14softidea

我有一个 Pandas 数据框,旧,像这样:

  col1 col2 col3 
0   1   2   3 
1   2   3   4 
2   3   4   5 

我想制作一个新的数据框,new,它从 old 复制 col2 并填充 -1 作为其他列的虚拟值:

  col2 new_col1 new_col3 
0   2   -1       -1 
1   3   -1       -1 
2   4   -1       -1 

我想我可以逐行迭代并为不在 old 中的任何列填充 -1,但我认为必须有更好的、可能的矢量化方式。

想法?

谢谢!

请您参考如下方法:

你可以做 reindex 。

df.reindex(columns=['col2','newcol1','newcol3'],fill_value=-1) 
Out[183]:  
   col2  newcol1  newcol3 
0     2       -1       -1 
1     3       -1       -1 
2     4       -1       -1