Numpy Pandas 刪除全為零的列的方法

2022-10-04 13:39:27 字數 1547 閱讀 1790

在處理numpy陣列,有這個需求,故寫下此文:

使用np.argwhere和np.all來查詢索引。要使用np.delete刪除它們。

示例1import numpy as np

a = np.arnmwmwray([[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]]

"""示例2import 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 arrawww.cppcns.comy (10, 20)

print("after array",array1程式設計客棧.shape) # after array (10, 17)

print("*****x*****\n",array1)

其它檢視:

pandas 刪除全零列

from pandas import dataframe

df1=dataframe(np.arange(16).reshape((4,4)),index=['a','b','c','d'],columns=['one','two','three','four']) # 建立乙個dataframe

df1.loc['e'] = 0 # 優雅地增加一行全0

df1.ix[(df1==0).all(axis=1), :] # 找到它

df1.ix[~(df1==0).all(axis=1), :] # 刪了它

numpy pandas基礎用法詳解

初學pandas不斷補充整理歸納常用的,配合numpy使用預設 import pandas as pd import numpy as np 習慣簡寫一 建立 1.seriess pd.series 1,3,4,np.nan,1 2.日期dates pd.date range 20180101 pe...

numpy pandas基礎入門(2)

在numpy中的基本運算,常用的有 乘方 dot 矩陣乘法 import numpy as np a np.array 1 2,3 b np.array 4 8,6 c1 a b 減法運算,對應位置元素相減 c2 a b 加法運算,對應位置元素相加 c3 a b 乘法運算,對應位置元素相乘 c4 a...

numpy pandas 計算雜訊特徵序列

出入t圈小菜雞,因工作需要學習了pandas numpy資料分析庫,謹以此帖,記錄經驗。如下圖所示,雜訊特徵幅度基本在0 1e13之間波動。請計算 data.npy資料中雜訊特徵幅度高於0.5e13所佔比例,並按自然小 時 0點 1點 統計該比例隨時間的分布。匯入原始資料 data pd.conca...