13

I read from a file with loadtxt like this

data = loadtxt(filename) # id x1 y1 x2 y2

data could look like

array([[   4.      ,  104.442848, -130.422137,  104.442848,  130.422137],
   [   5.      ,    1.      ,    2.      ,    3.      ,    4.      ]])

I can then reduce data to the lines belonging to some id number:

d = data [ data[:,0] == id] 

The problem here is when the data contain only one line.

So my question is how to check the 2-dimensionality of my array data?

I tried checking

data.shape[0]  # num of lines

but for one-liners I get something like (n, ), so this will not work.

Any ideas how to do this correctly?

3 Answers 3

18

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

1
  • 1
    Wow 50 secs to get an answer! Thanks!!
    – Tengis
    Nov 24, 2012 at 19:21
1

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
2
  • 1
    Example 1 does not work as you state. The Output of Example 2 would actually be "1-D array". It would have to be a recursive loop function to find the dimension of the array. You'd also have to check every element to determine the full dimensions, as data[0] could technically vary in length from data[1].
    – ryry1985
    Jan 4, 2022 at 23:15
  • 2
    Example 1 is plain wrong. It happens to output 2 because the length of the outer array is 2, not because it's a 2-D array. Jul 16 at 20:17
0

one more way:

Look for array.shape:

if it comes like (2,) means digit at first place but nothing after after comma,its 1D. Else if it comes like (2,10) means two digits with comma,its 2D. Similarly how many digits available with comma, that many dimensional array it is.

Simple "array.shape" will help you know that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.