[英]Python/Pandas: Sort dataframe columns based on a column name
I have a dataframe containing several columns labelled x1, x2, x3, and x4.我有一个 dataframe 包含标记为 x1、x2、x3 和 x4 的几列。
Depending on the analysis, I would need to assign one of the four columns to be the first column when ordering the four columns in the dataframe from left-to-right.根据分析,当从左到右对 dataframe 中的四列进行排序时,我需要将四列中的一列指定为第一列。
For instance, if I want column 'x2' to be the first I assign it to 'sorter'.例如,如果我希望列 'x2' 是第一个,我将其分配给 'sorter'。
sorter = x2
Now my question: how I sort the dataframes in the column so that the column assigned to 'sorter' is located in the first column?现在我的问题是:如何对列中的数据框进行排序,以便分配给“排序器”的列位于第一列?
EDIT: The order of the rest of the columns should remain unchanged.编辑:列的 rest 的顺序应保持不变。
You can change order of columns like:您可以更改列的顺序,例如:
data = {'X1': ['11', '12'],
'X2': ['21', '22'],
'X3': ['31', '32']
}
df = pd.DataFrame(data)
df
X1 X2 X3
0 11 21 31
1 12 22 32
df = df.reindex(['X3','X1','X2'], axis=1)
df
X3 X1 X2
0 31 11 21
1 32 12 22
Note: You need to provide desired order.注意:您需要提供所需的订单。
You can create a function to change order by given column:您可以创建 function 以按给定列更改顺序:
def sorter(desired, df):
columns = df.columns.tolist()
columns.remove(desired)
columns.insert(0,desired)
return df.reindex(columns, axis=1)
sorter('X2',df)
X2 X1 X3
0 21 11 31
1 22 12 32
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.