bis*_*smo 6 python string string-formatting dataframe pandas
我想删除数据框中以“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
Run Code Online (Sandbox Code Playgroud)
我知道这是某种字符串格式。我尝试使用 [-1] 对最后一个字母进行索引,但无法完全正常工作。谢谢!
除了@David的答案之外,您还可以使用 pandas strendswith来排除以 '_y' 结尾的列:
df.loc[:,~df.columns.str.endswith('_y')]
Team Color
0 1 red
1 2 green
2 3 blue
Run Code Online (Sandbox Code Playgroud)
~(波形符) 符号用作否定
pyjanitor select_columns的抽象可能会有所帮助:
df.loc[:,~df.columns.str.endswith('_y')]
Team Color
0 1 red
1 2 green
2 3 blue
Run Code Online (Sandbox Code Playgroud)
df.drop([col for col in df.columns if '_y' in col],axis=1,inplace=True)
Run Code Online (Sandbox Code Playgroud)
更好的是,如果它必须特定于它结尾,那么:
df.drop([col for col in df.columns if col.endswith('_y')],axis=1,inplace=True)
Run Code Online (Sandbox Code Playgroud)