Numpy(Pandas)刪除全為零的列的方法
在處理numpy數(shù)組,有這個需求,故寫下此文:
使用np.argwhere和np.all來查找索引。要使用np.delete刪除它們。
示例1
import numpy as np a = np.array([[1, 2, 0, 3, 0], [4, 5, 0, 6, 0], [7, 8, 0, 9, 0]]) idx = np.argwhere(np.all(a[..., :] == 0, axis=0)) a2 = np.delete(a, idx, axis=1) print(a2) """ [[1 2 3] [4 5 6] [7 8 9]] """
示例2
import numpy as np array1 = np.array([[1,0,1,0,0,0,0,0,0,1,1,0,0,0,1,1,0,1,0,0], [0,1,1,0,0,1,1,1,1,0,0,0,1,0,1,0,0,1,1,1], [0,0,1,0,0,1,1,1,0,0,0,0,0,0,0,1,0,0,1,1], [0,1,1,0,0,1,1,1,1,0,1,1,1,0,0,1,0,0,1,1], [0,0,1,0,0,1,1,1,0,1,0,1,1,0,1,1,0,0,1,0], [1,0,1,0,0,0,1,0,0,1,1,1,1,0,1,1,0,0,1,0], [1,0,1,0,1,1,0,0,0,0,1,0,0,0,1,0,0,0,1,1], [0,1,0,0,1,0,0,0,1,0,1,1,1,0,1,0,0,1,1,0], [0,1,0,0,1,0,0,1,1,0,1,1,1,0,0,1,0,1,0,0], [1,0,0,0,0,1,0,1,0,0,0,1,1,0,0,1,0,1,0,0]]) mask = (array1 == 0).all(0) column_indices = np.where(mask)[0] array1 = array1[:,~mask] print("raw array", array1.shape) # raw array (10, 20) print("after array",array1.shape) # after array (10, 17) print("=====x=====\n",array1)
其它查看:https://moonbooks.org/Articles/How-to-remove-array-rows-that-contain-only-0-in-python/
pandas 刪除全零列
from pandas import DataFrame df1=DataFrame(np.arange(16).reshape((4,4)),index=['a','b','c','d'],columns=['one','two','three','four']) # 創(chuàng)建一個dataframe df1.loc['e'] = 0 # 優(yōu)雅地增加一行全0 df1.ix[(df1==0).all(axis=1), :] # 找到它 df1.ix[~(df1==0).all(axis=1), :] # 刪了它
到此這篇關(guān)于Numpy(Pandas)刪除全為零的列的方法的文章就介紹到這了,更多相關(guān)Numpy刪除全為零的列內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python連接mysql數(shù)據(jù)庫并讀取數(shù)據(jù)的實現(xiàn)
這篇文章主要介紹了python連接mysql數(shù)據(jù)庫并讀取數(shù)據(jù)的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09Python函數(shù)式編程模塊functools的使用與實踐
本文主要介紹了Python函數(shù)式編程模塊functools的使用與實踐,教你如何使用?functools.partial、functools.wraps、functools.lru_cache?和?functools.reduce,感興趣的可以了解一下2024-03-03Python-jenkins 獲取job構(gòu)建信息方式
這篇文章主要介紹了Python-jenkins 獲取job構(gòu)建信息方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05