![](/img/trans.png)
[英]Drop columns whose name contains a specific string from pandas DataFrame
[英]Drop the first (or any nth) column whose name contains a specific string from pandas DataFrame
假设我有一个 pandas DataFrame 如下:
df = pd.DataFrame([[1,2,3,4,5],[6,7,8,9,10]],columns=['a1693','b1124','b113','a2609', 'a1'])
例如,我想删除b1124
。 我该怎么做?
我可以使用以下代码将该列作为 pd.Series 获取。
df.loc[:,df.columns.str.contains('b')].iloc[:,0]
但我不知道如何从df
中删除它。
另外,如果我想对多个列执行相同的操作,即删除a1693
和b1124
,我该怎么做呢?
添加过滤器
df = df.drop(df.columns[df.columns.str.contains('b')][0],1)
a1693 b113 a2609 a1
0 1 3 4 5
1 6 8 9 10
In [28]: N = 0
In [29]: df.drop(df.columns[np.where(df.columns.str.contains("b")==True)[0][N]], axis=1)
Out[29]:
a1693 b113 a2609 a1
0 1 3 4 5
1 6 8 9 10
In [30]: N = 1
In [31]: df.drop(df.columns[np.where(df.columns.str.contains("b")==True)[0][N]], axis=1)
Out[31]:
a1693 b1124 a2609 a1
0 1 2 4 5
1 6 7 9 10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.