Let's say I have a pandas DataFrame as follows:
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
. How do I do it?
I can get the column as a pd.Series by using the following code.
df.loc[:,df.columns.str.contains('b')].iloc[:,0]
But I don't know how to drop it from df
.
Also, if I want to do the same for multiple columns, ie drop a1693
and b1124
, how do I do that as well?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.