python - 如何根据正则表达式重新排序列?
问题描述
假设我有一个这样的数据框:
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
我想知道是否有更有效的方法来做到这一点。
解决方案
仅使用列表推导,将列表连接在一起并按以下方式选择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
推荐阅读
- ios - 如何在 Swift 中立即重绘标签(NSTextField)?
- c - 为什么指针不再引用它分配的内存?
- scala - Flink kafka 消费者无法反序列化来自 kafka 的 avro 数据
- c++ - 线程很慢 c++
- java - 如何在 android studio 中使用 MpAndroidChart 库实现实时烛台图?
- javascript - 定位一个 div 以在之后插入内容
- spring - 无法将 [org.springframework.web.multipart.MultipartFile] 类型的值转换为所需类型 [java.lang.String]
- linux - 如何使用 GStreamer 正确连接 mp4 视频
- python - 如何将 2 个参数传递给 def get_queryset?
- swift - 一种在 Swift 中读取和写入原语到内存缓冲区的简单方法