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

2024-10-03 23:24:12 发布

您现在位置:Python中文网/ 问答频道 /正文

不可预测的格式化df

  First Name  number last_name
0    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  other
0    Cthulhu     666     Smith    NaN

初始列的顺序需要与TemplateColumns相同,将剩余列保留在末尾,以获得desired_df

  First Name  other   number last_name
0    Cthulhu    NaN      666     Smith

desired_df = pd.DataFrame({'First Name': ['Cthulhu'], 'other': [np.nan], 'number': [666], 'last_name': ['Smith']})

对列进行重新排序是well explained in other posts,但我不知道如何对前n列进行排序,并将其余列保留在末尾。我该怎么做


Tags: nameinnumberdataframedf顺序colfirst
3条回答

试试这个

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

您可以编写自己的函数来实现这一点。基本上,您可以使用.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

像这样使用^{}

for col in TemplateColumns:
    if col not in df:
        df.insert(1, col, np.nan)

相关问题 更多 >