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

标签 python pandas

我有一个 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

关于python - Pandas:从其他 Dataframe 中的某些列创建新 Dataframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52267256/

相关文章:

python - 如何确定 Python 中对象的大小?

带有 StringIO 的 Python3 错误 : initial_value must be str or None,

python - 保存时 Pandas 的身材正在被削减

python : choose only users that have purchased more than x element

python - 使用 Python 请求模块时尝试/除外

python - 创建非冗余相关矩阵Python最有效的方法?

python - 在数字列表中隐藏二进制值

python - 基于其他列将函数应用于 Pandas 列

Python-Pandas : How to sort a pivot table maintaining one column grouped

python - Pandas 数据帧 : resample with linear interpolation