python - 通过多个正则表达式对 DataFrame 列进行排序

标签 python regex pandas dataframe

我想通过多个正则表达式来订购一个 DataFrame。也就是说,例如在这个DataFrame中

df = pd.DataFrame({'Col1': [20, 30],
                    'Col2': [50, 60],
                    'Pol2': [50, 60]})

在以 C 开头的列之前获取以 P 开头的列。

我发现你可以用一个正则表达式来过滤

df.filter(regex = "P*")

但我不能用更多的级别来做到这一点。

更新: 我想在一条指令中做到这一点,我已经能够使用正则表达式列表并连接另一个 DataFrame 中的列。

最佳答案

我相信你需要用 concat 列表中的正则表达式过滤的 DataFrame 列表:

reg = ['^P','^C']
df1 = pd.concat([df.filter(regex = r) for r in reg], axis=1)
print (df1)
   Pol2  Col1  Col2
0    50    20    50
1    60    30    60

关于python - 通过多个正则表达式对 DataFrame 列进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56898096/

相关文章:

python - 在 Python 中,将文本转换为 Zip 转换为 base64,反之亦然

c# - .NET 正则表达式,只有数字,没有空格

python - 使用 re.findall() 替换所有匹配项

python - 嵌套树 DataFrame reshape

python-3.x - 在 groupby 中应用 pandas cut

Python dateutil parser.parse ("On") 与今天一样

python - 在 Python 中迭代 Stern-Brocot 树的部分内容

python - 在 Python 中使用其名称(Python 字符串)获取枚举中的 C 变量值

regex - 如何在 Google 电子表格中使用 RegExReplace

python - Pandas 数据框列表的迭代性能变化很大