[英]Drop the first (or any nth) column whose name contains a specific string from pandas DataFrame
Let's say I have a pandas DataFrame as follows:假设我有一个 pandas DataFrame 如下:
df = pd.DataFrame([[1,2,3,4,5],[6,7,8,9,10]],columns=['a1693','b1124','b113','a2609', 'a1'])
I want to drop, for example, b1124
.例如,我想删除
b1124
。 How do I do it?我该怎么做?
I can get the column as a pd.Series by using the following code.我可以使用以下代码将该列作为 pd.Series 获取。
df.loc[:,df.columns.str.contains('b')].iloc[:,0]
But I don't know how to drop it from df
.但我不知道如何从
df
中删除它。
Also, if I want to do the same for multiple columns, ie drop a1693
and b1124
, how do I do that as well?另外,如果我想对多个列执行相同的操作,即删除
a1693
和b1124
,我该怎么做呢?
add filter添加过滤器
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.