Skip to main content
 首页 » 编程设计

python之按顺序固定列

2024年09月07日16落叶

我已经粘贴了下面给出的 df 的一些部分,但我在实际 df 中有超过 400 列。

 >>> df_final 
   c   d name  e   f  g   h  g   h 
0  0   0   aa  0   0  0   0  0   0 
1  1   2   bb  1   2  1   2  1   2 
2  2   4   cc  2   4  2   4  2   4 
3  3   6   dd  3   6  3   6  3   6 
4  4   8   ee  4   8  4   8  4   8 
5  5  10   ff  5  10  5  10  5  10 
6  6  12   gg  6  12  6  12  6  12 

我想要 'name' 和 'c' 以及第一和第二位置,但其他列的顺序无关紧要。我想用

cols = ['name' , 'c'] 
col_position = [1 , 2] 

如何使用列表 cols 和 col_position 重新排序数据框? 如何将列的数据类型设置为 str,其他列的数据类型设置为 float?

提前致谢

请您参考如下方法:

我认为需要:

df1 = df[cols + np.setdiff1d(df.columns, cols).tolist()] 
print (df1) 
 name  c   d  e   f  g  g.1   h  h.1 
0   aa  0   0  0   0  0    0   0    0 
1   bb  1   2  1   2  1    1   2    2 
2   cc  2   4  2   4  2    2   4    4 
3   dd  3   6  3   6  3    3   6    6 
4   ee  4   8  4   8  4    4   8    8 
5   ff  5  10  5  10  5    5  10   10 
6   gg  6  12  6  12  6    6  12   12 

和:

c1 = df.columns[col_position].tolist() 
df1 = df[c1 + np.setdiff1d(df.columns, c1).tolist()] 
print (df1) 
    d name  c  e   f  g  g.1   h  h.1 
0   0   aa  0  0   0  0    0   0    0 
1   2   bb  1  1   2  1    1   2    2 
2   4   cc  2  2   4  2    2   4    4 
3   6   dd  3  3   6  3    3   6    6 
4   8   ee  4  4   8  4    4   8    8 
5  10   ff  5  5  10  5    5  10   10 
6  12   gg  6  6  12  6    6  12   12 

按位置选择的替代方案:

c1 = np.arange(len(df.columns)) 
df1 = df.iloc[:, col_position + np.setdiff1d(c1, col_position).tolist()] 
print (df1) 
    d name  c  e   f  g   h  g.1  h.1 
0   0   aa  0  0   0  0   0    0    0 
1   2   bb  1  1   2  1   2    1    2 
2   4   cc  2  2   4  2   4    2    4 
3   6   dd  3  3   6  3   6    3    6 
4   8   ee  4  4   8  4   8    4    8 
5  10   ff  5  5  10  5  10    5   10 
6  12   gg  6  6  12  6  12    6   12