我在 python 中有以下列名数组。
col = ['code','ro','quantity','amount']
Run Code Online (Sandbox Code Playgroud)
我从一个函数获取处理后的数据帧,该函数可能具有也可能不具有上述所有列。如果数组中缺少这些列,我想添加默认值为 0 的列。
例如我得到以下数据框
df1
code ro quantity
123 342 34.56
123 445 54.56
Run Code Online (Sandbox Code Playgroud)
我想要的数据框是
code ro quantity amount
123 342 34.56 0
123 445 54.56 0
Run Code Online (Sandbox Code Playgroud)
我怎样才能在熊猫中做到这一点?
使用reindex超过axis=1:
df.reindex(col,fill_value=0,axis=1)
Run Code Online (Sandbox Code Playgroud)
code ro quantity amount
0 123 342 34.56 0
1 123 445 54.56 0
Run Code Online (Sandbox Code Playgroud)