【问题标题】:Order DataFrame columns by multiple regex通过多个正则表达式对 DataFrame 列进行排序
【发布时间】:2019-11-15 19:04:57
【问题描述】:

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

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

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

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

df.filter(regex = "P*")

但我无法通过更多关卡来做到这一点。

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

【问题讨论】:

    标签: python regex pandas dataframe


    【解决方案1】:

    我相信您需要由concat 列表中的正则表达式过滤的数据帧列表:

    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
    

    【讨论】:

    • 看看我几秒钟前的更新。还是谢谢你
    • @Angelo - 不确定是否理解but I can't do that with more levels.你能解释更多吗?
    【解决方案2】:

    您可以通过常规分配对列重新排序。

    将列导出到排序列表,并按其索引。

    尝试:

    import pandas as pd
    
    df = pd.DataFrame({'Col1': [20, 30],
                       'Pol2': [50, 60],
                        'Col2': [50, 60],
                        })
    
    df = df[sorted(df.columns.to_list(), key=lambda col: col.startswith("P"), reverse=True)]
    
    print(df)
    

    【讨论】:

    • 注意:如果您需要更复杂的正则表达式,您可以根据需要修改key
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 2018-08-24
    • 1970-01-01
    • 2014-09-11
    相关资源
    最近更新 更多