gpt4 book ai didi

python - 如果数据框中不存在,如何在 Pandas 中添加列

转载 作者:太空宇宙 更新时间:2023-11-04 11:17:25 24 4
gpt4 key购买 nike

我在 python 中有以下列名数组。

 col = ['code','ro','quantity','amount']

我从一个可能有也可能没有上述所有列的函数中得到处理过的数据框。如果数组中缺少它们,我想添加默认值为 0 的列。

例如我得到以下数据框

df1

code ro quantity
123 342 34.56
123 445 54.56

我想要的数据框是

code      ro      quantity  amount
123 342 34.56 0
123 445 54.56 0

我怎样才能在 pandas 中做到这一点?

最佳答案

使用reindexaxis=1 上:

df.reindex(col,fill_value=0,axis=1)

   code   ro  quantity  amount
0 123 342 34.56 0
1 123 445 54.56 0

关于python - 如果数据框中不存在,如何在 Pandas 中添加列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56721880/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com