![](/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.