为了账号安全,请及时绑定邮箱和手机立即绑定

如何对前 n 个数据框列重新排序,并在末尾添加剩余的列?

如何对前 n 个数据框列重新排序,并在末尾添加剩余的列?

撒科打诨 2023-12-08 14:54:12
不可预测的格式df:  First Name  number last_name0    Cthulhu     666     Smith    df = pd.DataFrame({'First Name': ['Cthulhu'], 'number': [666], 'last_name': ['Smith']})这需要放入列名称和顺序中:TemplateColumns = ['First Name', 'other', 'number']。如果列不存在,可以创建它们:for col in TemplateColumns:    if col not in df:        df[col] = np.nan这使:  First Name  number last_name  other0    Cthulhu     666     Smith    NaN初始列需要与 一样排序TemplateColumns,将剩余列留在最后,以获得desired_df:  First Name  other   number last_name0    Cthulhu    NaN      666     Smithdesired_df = pd.DataFrame({'First Name': ['Cthulhu'], 'other': [np.nan], 'number': [666], 'last_name': ['Smith']})重新排序列在其他帖子中得到了很好的解释,但我不知道如何对前 n 列进行排序并将其余的保留在最后。我怎样才能做到这一点?
查看完整描述

3 回答

?
MYYA

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


查看完整回答
反对 回复 2023-12-08
?
白衣非少年

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


查看完整回答
反对 回复 2023-12-08
?
PIPIONE

TA贡献1829条经验 获得超9个赞

insert像这样使用:


for col in TemplateColumns:

    if col not in df:

        df.insert(1, col, np.nan)


查看完整回答
反对 回复 2023-12-08
  • 3 回答
  • 0 关注
  • 64 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信