如何根据名称中的某个字符串删除数据框列?
示例:
house1 house2 chair1 chair2
index
1 foo lee sam han
2 fowler smith had sid
3 cle meg mag mog
我想删除字符串中包含'chair'的列。 如何以有效的方式完成? 感谢。
答案 0 :(得分:8)
auto-complete
答案 1 :(得分:5)
<强> UPDATE2:强>
In [315]: df
Out[315]:
3M110% 3M80% 6M90% 6M95% 1N90% 2M110% 3M95%
1 foo lee sam han aaa aaa fff
2 fowler smith had sid aaa aaa fff
3 cle meg mag mog aaa aaa fff
In [316]: df.loc[:, ~df.columns.str.contains('90|110')]
Out[316]:
3M80% 6M95% 3M95%
1 lee han fff
2 smith sid fff
3 meg mog fff
<强>更新强>
In [40]: df
Out[40]:
house1 house2 chair1 chair2 door1 window1 floor1
1 foo lee sam han aaa aaa fff
2 fowler smith had sid aaa aaa fff
3 cle meg mag mog aaa aaa fff
In [41]: df.filter(regex='^(?!(chair|door|window).*?)')
Out[41]:
house1 house2 floor1
1 foo lee fff
2 fowler smith fff
3 cle meg fff
原始回答:
这里有一些选择:
In [37]: df.drop(df.filter(like='chair').columns, 1)
Out[37]:
house1 house2
1 foo lee
2 fowler smith
3 cle meg
In [38]: df.filter(regex='^(?!chair.*)')
Out[38]:
house1 house2
1 foo lee
2 fowler smith
3 cle meg
答案 2 :(得分:4)
答案 3 :(得分:3)
还有一个选择:
import pandas as pd
df = pd.DataFrame({'house1':['foo','fowler','cle'],
'house2':['lee','smith','meg'],
'chair1':['sam','had','mag'],
'chair2':['han','sid','mog']})
mask = ['chair' not in x for x in df]
df = df[df.columns[mask]]