添加 "nan" 到 numpy 直方图 python
Add "nan" to numpy histogram python
我正在使用随机库从高斯分布生成 5000 个数据点,然后使用这些数据计算具有 10 个 bin 的直方图,请参见下面的代码。
s = np.random.normal(mu, sigma, 5000)
arrHist = np.histogram(s, 10)
print(arrHist)
输出为:
(array([ 9, 48, 282, 800, 1436, 1424, 742, 216, 40, 3]),
array([1.52017489, 1.61690575, 1.71363661, 1.81036747, 1.90709834,
2.0038292 , 2.10056006, 2.19729092, 2.29402179, 2.39075265,
2.48748351]))
如您所见,数组长度不同,因此我想将 np.nan
添加到较短的数组中,以便数组长度相同。我知道可以使用 np.append
将值附加到数组的末尾,但是当 arrHist
中有两个数组时我该怎么做?
我是 python 的新手,因此非常感谢您的帮助。提前致谢。
试试这个:
result=[]
max_len=max([len(x) for x in arrHist])
for x in arrHist:
if len(x)!=max_len:
x=x.astype('float')
x=np.pad(x, (0,max_len-len(x)), 'constant', constant_values=(np.nan, ))
result.append(x)
我正在使用随机库从高斯分布生成 5000 个数据点,然后使用这些数据计算具有 10 个 bin 的直方图,请参见下面的代码。
s = np.random.normal(mu, sigma, 5000)
arrHist = np.histogram(s, 10)
print(arrHist)
输出为:
(array([ 9, 48, 282, 800, 1436, 1424, 742, 216, 40, 3]),
array([1.52017489, 1.61690575, 1.71363661, 1.81036747, 1.90709834,
2.0038292 , 2.10056006, 2.19729092, 2.29402179, 2.39075265,
2.48748351]))
如您所见,数组长度不同,因此我想将 np.nan
添加到较短的数组中,以便数组长度相同。我知道可以使用 np.append
将值附加到数组的末尾,但是当 arrHist
中有两个数组时我该怎么做?
我是 python 的新手,因此非常感谢您的帮助。提前致谢。
试试这个:
result=[]
max_len=max([len(x) for x in arrHist])
for x in arrHist:
if len(x)!=max_len:
x=x.astype('float')
x=np.pad(x, (0,max_len-len(x)), 'constant', constant_values=(np.nan, ))
result.append(x)