不可预测的格式化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列进行排序,并将其余列保留在末尾。我该怎么做
试试这个
您可以编写自己的函数来实现这一点。基本上,您可以使用
.reindex()
对数据帧进行重新排序,同时如果不存在空列,则可以包括空列。剩下要解决的唯一问题是如何将TemplateColumns
中没有的其余列添加到数据帧中。您可以通过从TemplateColumns
获取列索引的集合差,然后在调用.reindex
之前更新顺序来完成此操作建立数据仓库;作用
与
include_remaining
一起:没有
include_remaining
:像这样使用^{} :
相关问题 更多 >
编程相关推荐