3 回答
TA贡献1868条经验 获得超4个赞
尝试这个
cols = TemplateColumns + df.columns.difference(TemplateColumns, sort=False).tolist()
df_final = df.reindex(cols, axis=1)
Out[714]:
First Name other number last_name
0 Cthulhu NaN 666 Smith
TA贡献1155条经验 获得超0个赞
您可以编写自己的函数来实现此目的。本质上,您可以用来.reindex()对数据框重新排序,同时包含空列(如果它们不存在)。唯一需要弄清楚的剩余部分是如何将剩余的列添加到TemplateColumns数据框中。您可以通过获取列索引的设置差异来完成此操作,然后TemplateColumns在调用之前更新订单.reindex
设置数据和功能
def reordered(df, new_order, include_remaining=True):
cols_to_end = []
if include_remaining:
# gets the items in `df.columns` that are NOT in `new_order`
cols_to_end = df.columns.difference(new_order, sort=False)
# Ensures that the new_order items are first
final_order = new_order + list(cols_to_end)
return df.reindex(columns=final_order)
df = pd.DataFrame({'First Name': ['Cthulhu'], 'number': [666], 'last_name': ['Smith']})
new_order = ['First Name', 'other', 'number']
和include_remaining:
out = reordered(df, new_order, include_remaining=True)
print(out)
First Name other number last_name
0 Cthulhu NaN 666 Smith
没有include_remaining:
out = reordered(df, new_order, include_remaining=False)
print(out)
First Name other number
0 Cthulhu NaN 666
TA贡献1829条经验 获得超9个赞
insert像这样使用:
for col in TemplateColumns:
if col not in df:
df.insert(1, col, np.nan)
添加回答
举报