簡體   English   中英

python numpy 矩陣逐行操作:每行中的列

[英]python numpy matrix row wise operations: columns in each row

如何遍歷矩陣並獲取每行的列數? 如果我有一個矩陣,並且矩陣中的某些元素是 NaN(空),例如:[[4,2,9,4],[3,4,8,6],[5,NaN,7,7] ,[Nan,8,Nan,Nan]],如何計算行長度?

我努力了:

len(matrix) # number of rows
=len(matrix[0]) # number of columns

但這給了我總數。

所以我想得到一個向量,表示每行中的列數:[4,4,3,1] 例如

我的想法是做一個這樣的循環:

for i in matrix:

然后是它搜索的循環。 但我不知道該怎么做

編輯:我嘗試了@wavy 的方法,它奏效了。 我可以這樣做:

# empty list
Final=[]

for i in range(matrix):
    columns=np.isnan(matrix).sum(axis=1)
    result=-columns+matrix.shape[1]
    if result==1:
        Final.append(matrix[i])
        
        
    print(Final)

I also need to put other conditions, when result==2, and when result>2

這可能比 David Wierichs 的建議更快:

import numpy as np 

x = np.array([[4, 2, 9, 4], [3, 4, 8, 6], [5, np.nan, 7, 7], [np.nan, 8, np.nan, np.nan]])
y = np.isnan(x).sum(axis=1)
result = -y + x.shape[1]

您可以遍歷行並為每一行使用(否定的) numpy.isnan 方法:

lengths = [np.sum(~np.isnan(row)) for row in matrix]

由於這會在np.isnan中建立一個 boolean 數組,因此可能會有更快的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM