首页 > 解决方案 > 如何根据正则表达式重新排序列?

问题描述

假设我有一个这样的数据框:

df = pd.DataFrame({'foo':[1, 2], 'bar': [3, 4], 'xyz': [5, 6]})

   bar  foo  xyz
0    3    1    5
1    4    2    6

我现在想将包含的列放在oo第一个位置(即第 0 个索引处);这种模式总是只有一列。

我目前使用filter两次和一个来解决这个问题concat

pd.concat([df.filter(like='oo'),  df.filter(regex='^((?!(oo)).)*$')], axis=1)

这给出了所需的输出:

   foo  bar  xyz
0    1    3    5
1    2    4    6

我想知道是否有更有效的方法来做到这一点。

标签: pythonregexpandas

解决方案


仅使用列表推导,将列表连接在一起并按以下方式选择subset

a = [x for x in df.columns if 'oo' in x]
b = [x for x in df.columns if not 'oo' in x]

df = df[a + b]
print (df)
   foo  bar  xyz
0    1    3    5
1    2    4    6

推荐阅读