首页 > 解决方案 > Python ValueError:无法连接零维数组

问题描述

我正在阅读一本名为“掌握 Python 数据分析”的书,但在数据建模练习中遇到了错误。我得到的错误是:

ValueError:无法连接零维数组

我不确定这个错误是什么意思或导致它的原因。

代码如下:

%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import os
from pandas import Series, DataFrame
import numpy.random as rnd
import scipy.stats as st

mean = 0
sdev = 1
nvalues = 10
norm_variate = mean * sdev +rnd.randn(nvalues)
print(norm_variate)

for i, v in enumerate(sorted(norm_variate), start = 1):
    print(('{0:2d} {1:+.4f}' .format(i,v)))

def plt_cdf(data, plot_range=None, scale_to=None, **kwargs):
    num_bins = len(data)
    sorted_data = np.array(sorted(data), dtype=np.float64)
    data_range = sorted_data[-1] - sorted_data[0]
    counts, bin_edges = np.histogram(sorted_data, bins=num_bins)
    xvalues = bin_edges[:1]
    yvalues = np.cumsum(counts)
    if plot_range is None:
        xmin = sorted_data[0]
        xmax = sorted_data[-1]
    else:
            xmin, xmax = plot_range
            # pad the arrays
            xvalues = np.concatenate([xmin, xvalues[0], xvalues, [xmax]])
            yvalues = np.concatenate([[0.0, 0.0], yvalues, [yvalues.max()]])
            if scale_to is not NONE:
                yvalues = yvalues / len(data) * scale_to
                plt.axis([xmin, xmax, 0, yvalues.max()])
                return plt.plt(xvalues, yvalues, **kwargs)

nvalues = 20
norm_variate = rnd.randn(nvalues)
plt_cdf(norm_variate, plot_range=[-3,3], scale_to=1.0, lw=2.5, color='Brown')
for v in [0.25, 0.5, 0.75]:
    plt.axhline(v, lw=1, ls='--', color='black')

任何帮助都感激不尽。

标签: pythonarraysnumpy

解决方案


制作一个简单的数组和几个标量值:

In [197]: x = np.arange(4)
In [198]: x0=x[0]; x1=x[-1]

尝试加入他们会产生错误:

In [199]: np.concatenate([x0, x, x1])
Traceback (most recent call last):
  File "<ipython-input-199-9131e46a3dcd>", line 1, in <module>
    np.concatenate([x0, x, x1])
  File "<__array_function__ internals>", line 5, in concatenate
ValueError: zero-dimensional arrays cannot be concatenated

但是添加 [] 来定义列表,因此添加 1 个元素数组,可以:

In [200]: np.concatenate([[x0], x, [x1]])
Out[200]: array([0, 0, 1, 2, 3, 3])

hstack做同样的事情 - 将任何标量转换为数组

In [201]: np.hstack([x0,x,x1])
Out[201]: array([0, 0, 1, 2, 3, 3])

跟踪尺寸是使用numpy. 不要做假设。尤其是有错误的时候,测试,再测试。


推荐阅读