【问题标题】:How to drop columns based on column name python pandas如何根据列名python pandas删除列
【发布时间】:2020-04-12 04:07:03
【问题描述】:

我想删除数据框中以“y”结尾的每一列。出于某种原因,我拥有的数据将每列列出了两次,唯一不同的是列名,如下所示:

d = {'Team': ['1', '2', '3'], 'Team_y': ['1', '2', '3'], 'Color' : ['red', 'green', 'blue'], 'Color_y' : ['red', 'green', 'blue']}
df = pd.DataFrame(data=d)
df

    Team    Team_y  Color   Color_y
0    1        1      red     red
1    2        2     green   green
2    3        3      blue    blue

我知道这是某种字符串格式。我尝试使用 [-1] 索引最后一个字母,但无法完全正常工作。谢谢!

【问题讨论】:

    标签: python string pandas dataframe string-formatting


    【解决方案1】:

    除了@David 的回答,您还可以使用 pandas str endswith 排除以 '_y' 结尾的列:

    df.loc[:,~df.columns.str.endswith('_y')]
    
      Team  Color
    0   1   red
    1   2   green
    2   3   blue
    

    〜(波浪号)符号用作否定

    【讨论】:

      【解决方案2】:

      drop column based on a string condition

      df.drop([col for col in df.columns if '_y' in col],axis=1,inplace=True)
      

      更好的是,如果它必须特定于以它结尾,那么:

      df.drop([col for col in df.columns if col.endswith('_y')],axis=1,inplace=True)
      

      【讨论】:

        【解决方案3】:

        通过正则表达式使用过滤器

        df = df[df.columns.drop(list(df.filter(regex='_y')))]
        

        【讨论】:

          猜你喜欢
          • 2021-12-06
          • 2015-04-16
          • 2021-01-08
          • 2015-04-22
          • 2020-12-11
          • 2022-10-15
          • 2017-09-15
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多