【问题标题】:Python: Selecting multiple similar columns from dataframePython:从数据框中选择多个相似的列
【发布时间】:2017-08-01 20:27:15
【问题描述】:

我有一个数据框:

df:

    a21   b21   c21  a22   b22  a23  b23
1    2    2      2    4     5    7    7
2    2    2      2    4     5    7    7
3    2    2      2    4     5    7    7
4    2    2      2    4     5    7    7
5    2    2      2    4     5    7    7

我只想选择具有'21''23' 的列,这样我的输出是:

df_output:

    a21   b21   c21   a23  b23
1    2    2      2     7    7
2    2    2      2     7    7
3    2    2      2     7    7
4    2    2      2     7    7
5    2    2      2     7    7

我可以用下面的代码做到这一点:

df_21 = (df.loc[:, df.filter(like='21').columns])    
df_23 = (df.loc[:, df.filter(like='23').columns])

然后我可以合并 df_21df_23 但是有没有一种有效的方法可以在一行代码中做同样的事情?

【问题讨论】:

    标签: python pandas dataframe multiple-columns


    【解决方案1】:

    我们可以使用DataFrame.filter()方法:

    In [38]: df.filter(regex=r'21|23')
    Out[38]:
       a21  b21  c21  a23  b23
    1    2    2    2    7    7
    2    2    2    2    7    7
    3    2    2    2    7    7
    4    2    2    2    7    7
    5    2    2    2    7    7
    

    或:

    In [45]: df.loc[:, df.columns.str.contains(r'21|23')]
    Out[45]:
       a21  b21  c21  a23  b23
    1    2    2    2    7    7
    2    2    2    2    7    7
    3    2    2    2    7    7
    4    2    2    2    7    7
    5    2    2    2    7    7
    

    【讨论】:

      【解决方案2】:

      您可以使用条件列表推导:

      targets = ['21', '23']
      df[[col for col in df if any(target in col for target in targets)]]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-10-13
        • 1970-01-01
        • 2019-03-10
        • 1970-01-01
        • 2022-06-11
        • 2019-12-24
        • 1970-01-01
        相关资源
        最近更新 更多