如何根据列名python pandas删除列

问题描述 投票:2回答:2

我想删除我数据框中所有以'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
2个回答
1
投票

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)

0
投票

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

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

0
投票

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

df.loc[:,~df.columns.str.endswith('_y')]

  Team  Color
0   1   red
1   2   green
2   3   blue

〜(波浪号)用作负号

© www.soinside.com 2019 - 2024. All rights reserved.