Introduction
When working with arrays in Python, especially with NumPy, you might encounter the ValueError: zero-dimensional arrays cannot be concatenated. This happens when trying to concatenate scalar values (zero-dimensional arrays) directly using numpy.concatenate()
. Fortunately, there are alternative methods like hstack()
and stack()
that ensure inputs have the correct dimensions for concatenation.
Example to Reproduce the Error
Let’s go through an example to trigger the error:
import numpy as np # Attempting to concatenate scalar values np.concatenate([1, 2, 3, 4])
Output:
ValueError: zero-dimensional arrays cannot be concatenated
Here, we attempted to concatenate scalar values (1, 2, 3, 4) directly using np.concatenate()
. Since scalars are zero-dimensional, NumPy throws an error because it can’t concatenate arrays with zero dimensions.
To avoid this error, we need to ensure that the values being concatenated have at least one dimension. One way to do this is by using functions like np.hstack()
or np.expand_dims()
that handle dimension adjustments automatically.
Solutions
1. Using np.hstack()
The hstack()
function takes care of reshaping scalars into 1-dimensional arrays. It applies np.atleast_1d()
internally, ensuring that all inputs have at least one dimension before concatenating them.
import numpy as np # Using hstack to concatenate scalars result = np.hstack([1, 2, 3, 4]) print(result) print(type(result))
Output:
[1 2 3 4] <class 'numpy.ndarray'>
Here, np.hstack()
automatically converts the scalars into 1-dimensional arrays and then concatenates them successfully.
2. Using np.stack()
The stack()
function is another alternative that can handle zero-dimensional arrays by explicitly specifying an axis along which to concatenate. It works similarly to hstack()
but gives more control over the axis:
import numpy as np # Using stack to concatenate scalars result = np.stack([np.expand_dims(i, axis=0) for i in [1, 2, 3, 4]]) print(result)
Output:
[[1] [2] [3] [4]]
3. Using np.array()
For most situations, the cleanest way to handle scalars is by using np.array()
to create an array from them in the first place, rather than concatenating individual scalars.
import numpy as np # Create an array directly from scalars result = np.array([1, 2, 3, 4]) print(result)
Output:
[1 2 3 4]
This is the most straightforward solution when you know you’re dealing with scalars and want to create an array from them.
Explanation of Dimensions in NumPy
It’s important to understand how dimensions work in NumPy arrays. When you create a scalar in NumPy:
scalar = np.array(1) print(scalar.shape)
Output:
()
The output shows that scalar
is a zero-dimensional array. Trying to concatenate this with higher-dimensional arrays results in an error, as shown in the previous example. When we convert scalars into 1-dimensional arrays, they can be concatenated without issues.
If you have multiple zero-dimensional arrays and wish to join them, consider what the resulting dimensionality will be. For example:
- Joining four zero-dimensional arrays on a common axis will give you four 1-dimensional elements.
- Joining four one-dimensional arrays can give you a 2D array (4, n) or (n, 4), depending on the axis.
Conclusion
The ValueError: zero-dimensional arrays cannot be concatenated in Python occurs when attempting to concatenate scalars using np.concatenate()
. This error can be easily solved using either np.hstack()
, np.stack()
, or simply creating an array using np.array()
.
In most cases, directly creating arrays with np.array()
or np.hstack()
will be the most convenient options for avoiding this error.
Congratulations on reading to the end of this tutorial!
For further reading on arithmetic operations with NumPy arrays and dimensions/shapes of arrays, go to the articles:
- How to Multiply Two Matrices in Python
- How to Solve Python ValueError: zero-dimensional arrays cannot be concatenated
- How to Solve Python ValueError: operands could not be broadcast together with shapes
Go to the online courses page on Python to learn more about coding in Python for data science and machine learning.
Have fun and happy researching!
Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.