Cle*_*leb 2 python regex pandas
假设我有一个像这样的数据框:
df = pd.DataFrame({'foo':[1, 2], 'bar': [3, 4], 'xyz': [5, 6]})
bar foo xyz
0 3 1 5
1 4 2 6
Run Code Online (Sandbox Code Playgroud)
我现在想将包含的列放在oo第一个位置(即第 0 个索引);始终只有一列具有这种模式。
我目前使用filter两次和一个来解决这个问题concat:
pd.concat([df.filter(like='oo'), df.filter(regex='^((?!(oo)).)*$')], axis=1)
Run Code Online (Sandbox Code Playgroud)
这给出了所需的输出:
foo bar xyz
0 1 3 5
1 2 4 6
Run Code Online (Sandbox Code Playgroud)
我想知道是否有更有效的方法来做到这一点。
仅使用列表理解,将列表连接在一起并选择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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
575 次 |
| 最近记录: |