【问题标题】:Select DataFrame columns with names that follow a given pattern in pandas [closed]选择名称遵循熊猫中给定模式的DataFrame列[关闭]
【发布时间】:2018-03-08 10:25:22
【问题描述】:

我正在使用包含大量列的DataFrame。我希望能够选择遵循给定模式的列子集。

例子

df = pd.DataFrame({'a_1': [1,2,3],'b': [2,3,4],'c_1': [3,4,5]})

   a_1  b  c_1
0    1  2    3
1    2  3    4
2    3  4    5

我希望能够只选择以_1 结尾的列(这可以使用正则表达式语法表示为'.*_1'),结果是:

   a_1  c_1
0    1    3
1    2    4
2    3    5

【问题讨论】:

    标签: python pandas dataframe pattern-matching selection


    【解决方案1】:

    对此有一种特殊的方法——DataFrame.filter():

    In [178]: df.filter(regex=r'_1$')
    Out[178]:
       a_1  c_1
    0    1    3
    1    2    4
    2    3    5
    

    【讨论】:

      【解决方案2】:

      使用boolean indexingendswith 掩码或contains 正则表达式:

      df1 = df.loc[:, df.columns.str.endswith('_1')]
      
      df1 = df.loc[:, df.columns.str.contains('_1$')]
      
      df1 = df.loc[:, df.columns.str.contains('.*_1')]
      

      print (df1)
         a_1  c_1
      0    1    3
      1    2    4
      2    3    5
      

      【讨论】:

      • 可以用正则表达式代替吗?
      • @KrzysztofSłowiński - 是的,需要第二个解决方案 contains
      • 谢谢,这是一个重复的问题,因为它被否决了吗?
      • @KrzysztofSłowiński - 你的问题被否决的主要原因是没有你的代码,你尝试了什么。
      • 好的,很高兴知道。
      【解决方案3】:

      您可以使用列表推导来选择以_1 结尾的列:

      df = pd.DataFrame({'a_1': [1,2,3], 'b': [2,3,4], 'c_1': [3,4,5]})
      filter_col = [col for col in df if col.endswith('_1')]
      
      df[filter_col]
      
         a_1  c_1
      0    1    3
      1    2    4
      2    3    5
      

      【讨论】:

      • 当然,我正在考虑一种更通用的方法,因此它不仅适用于这种特殊情况,这就是选择使用正则表达式的解决方案的原因。
      • 没问题。你可以接受满足你需求的答案:)
      猜你喜欢
      • 2018-03-13
      • 2018-10-29
      • 2016-08-18
      • 1970-01-01
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      • 2020-03-22
      • 1970-01-01
      相关资源
      最近更新 更多