2013-08-22 45 views
2

我有一个2D数组,我试图绘制一列中所有行的直方图,给出另一列中的条件。我试图在plt.hist()命令中选择子数据,以避免创建众多的子数组,我已经知道该如何做。例如,如果matplotlib:如何从二维数组有条件地绘制直方图

a_long_named_array = [1, 5] 
        [2, 6] 
        [3, 7] 

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

a_long_named_subarray = a_long_named_array[a_long_named_array[:,1] > 5] 

如何绘制这个子数据未做上述子阵?请看下面。

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() 

回答

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] 

基本上,地方:的,你只是把布尔掩码(something > 5)。您可能会发现它更清晰的写:

mask = arr[:,1] > 5 
result = arr[mask, 0] 

的这一思想的另一种方法是:

second_column = arr[:,1] 
first_column = arr[:,0] 
print first_column[second_column > 5] 
相关问题