matplotlib:如何从二维数组中有条件地绘制直方图

ast*_*erd 2 python numpy matplotlib

我有一个2D数组,在这里我试图绘制一列中所有行的直方图,给定另一列中的条件.我试图在plt.hist()命令中选择子数据,以避免产生许多子数组,我已经知道如何做.例如,如果

a_long_named_array = [1, 5]
                     [2, 6]
                     [3, 7]
Run Code Online (Sandbox Code Playgroud)

我可以通过写入创建我的数组的子集,使第1列大于5

a_long_named_subarray = a_long_named_array[a_long_named_array[:,1] > 5]
Run Code Online (Sandbox Code Playgroud)

如何在不制作上述子阵列的情况下绘制此子数据?请看下面.

import numpy as np
import matplotlib.pyplot as plt

#Generate 2D array
arr = np.array([np.random.random_integers(0,10, 10), np.arange(0,10)])

#Transpose it
arr = arr.T

#----------------------------------------------------------------------------
#Plotting a Histogram: This works
#----------------------------------------------------------------------------

#Plot all the rows of the 0'th column
plt.hist(arr[:,0])
plt.show()

#----------------------------------------------------------------------------
#Plotting a conditional Histogram: This is what I am trying to do. This Doesn't work.
#----------------------------------------------------------------------------

#Plot all the rows of the 0th column where the 1st column is some condition (here > 5)
plt.hist(arr[:,0, where 1 > 5])
plt.show()

quit()
Run Code Online (Sandbox Code Playgroud)

Joe*_*ton 5

您只需要将布尔索引(whatever > 5返回布尔数组)应用于第一个维度.

您当前正尝试使用布尔掩码沿第三维索引数组.该数组只是2D,所以你可能会得到一个IndexError.(很可能是" IndexError: too many indices".)

例如:

import numpy as np

# Your example data
arr = np.array([np.random.random_integers(0,10, 10), np.arange(0,10)])
arr = arr.T

# What you want:
print arr[arr[:,1] > 5, 0]
Run Code Online (Sandbox Code Playgroud)

基本上,代替:你,你只需要输入布尔值掩码(something > 5).你可能会发现写起来更清楚:

mask = arr[:,1] > 5
result = arr[mask, 0]
Run Code Online (Sandbox Code Playgroud)

另一种思考方式是:

second_column = arr[:,1]
first_column = arr[:,0]
print first_column[second_column > 5]
Run Code Online (Sandbox Code Playgroud)