pandas 对大型数据框中的选定列重新排序

wxclj1h5  于 2023-08-01  发布在  其他
关注(0)|答案(1)|浏览(131)

我有一个很大的pandas dataframe -假设有150列,每次代码运行时,它甚至会增长。我正在寻找的是,如何将选定的几个列带到数据框架的前面(我知道它将永远存在)。

oknwwptz

oknwwptz1#

您可以使用索引intersection/union

  1. cols = ['E', 'A', 'B']
  2. out = df[pd.Index(cols).intersection(df.columns).union(df.columns, sort=False)]

字符串
如果确定cols只包含有效列:

  1. out = df[pd.Index(cols).union(df.columns, sort=False)]


输出量:

  1. E A B C D F G H
  2. 0 4 0 1 2 3 5 6 7


使用的输入:

  1. A B C D E F G H
  2. 0 0 1 2 3 4 5 6 7


如果要将列放在前面,但保持其相对原始顺序,则可以选择:

  1. out = df.sort_index(axis=1, key=lambda x: x.isin(cols), ascending=False)


输出量:

  1. A B E C D F G H
  2. 0 0 1 4 2 3 5 6 7

展开查看全部

相关问题