How to check if an array is 2D

You can always check the dimension of your array with len(array) function.

Example1:

data = [[1,2],[3,4]]
if len(data) == 1:
   print('1-D array')
if len(data) == 2:
   print('2-D array')
if len(data) == 3:
   print('3-D array')

Output:

2-D array

And if your array is a Numpy array you can check dimension with len(array.shape).

Example2:

import Numpy as np
data = np.asarray([[1,2],[3,4]])
if len(data.shape) == 1:
   print('1-D array')
if len(data.shape) == 2:
   print('2-D array')
if len(data.shape) == 3:
   print('3-D array')

Output:

2-D array

data.ndim gives the dimension (what numpy calls the number of axes) of the array.


As you already have observed, when a data file only has one line, np.loadtxt returns a 1D-array. When the data file has more than one line, np.loadtxt returns a 2D-array.

The easiest way to ensure data is 2D is to pass ndmin=2 to loadtxt:

data = np.loadtxt(filename, ndmin=2)

The ndmin parameter was added in NumPy version 1.6.0. For older versions, you could use np.atleast_2d:

data = np.atleast_2d(np.loadtxt(filename))

Tags:

Python

Numpy