aguadamuz
aguadamuz

Reputation: 421

Python ValueError: zero-dimensional arrays cannot be concatenated

I am working through a book named 'Mastering Python Data Analysis' and I am getting an error on one the data modeling exercises. The error I am getting is:

ValueError: zero-dimensional arrays cannot be concatenated

I am not sure what this error means or what is causing it.

The code is as follows:

%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')

Any help will be much appreciated.

Upvotes: 0

Views: 2763

Answers (1)

hpaulj
hpaulj

Reputation: 231615

Make a simple array, and a couple of scalar values:

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

trying to join them produces your error:

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

But adding [] to define lists, and hence 1 element arrays, works:

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

hstack does the same thing - turning any scalars in to arrays

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

Keeping track of dimensions is an important part of using numpy. Don't make assumptions. Especially when there are errors, test, and test again.

Upvotes: 1

Related Questions