我有9x9维度的数组 A 。我想选择特定的行,例如2,5,6和7并计算每行的最小值。
我试过
将numpy导入为np
将pandas导入为pd
A.min(轴= 1)
array([0, 0, 0, 0, 0, 0, 0, 0, 0])
但它同时为所有行提供值。我只想要特定的行。
答案 0 :(得分:0)
如果df
是包含dh.shape == (9, 9)
的NumPy数组,要获得大于零的最小值,您可以例如做
row2 = df[2] # or df[2, :] to choose all columns explicitly
min2 = np.min(row2[row2 > 0])
row5 = df[5] # or df[5, :] to choose all columns explicitly
min5 = np.min(row5[row5 > 0])
...
答案 1 :(得分:0)
然后我们需要做一些改变。
min_nums = []
for rows in matrix:
rows = [y for y in rows if y > 0] ## If you want to include negative numbers then replace ">" with "!="
min_nums.append(min(rows))
其中min_nums是给定行的最小值列表,矩阵将是您给定的矩阵。 (2,5,6,7是矩阵中行的索引)
答案 2 :(得分:0)
使用数组,通过索引选择所需的行,然后应用min
:
In [16]: x=np.arange(81).reshape(9,9)
In [17]: idx=[2,5,6,7]
In [18]: x[idx,:].min(axis=1)
Out[18]: array([18, 45, 54, 63])
In [19]: x[idx,:]
Out[19]:
array([[18, 19, 20, 21, 22, 23, 24, 25, 26],
[45, 46, 47, 48, 49, 50, 51, 52, 53],
[54, 55, 56, 57, 58, 59, 60, 61, 62],
[63, 64, 65, 66, 67, 68, 69, 70, 71]])