0

I read linewise data from a file and I want to store them in an array.

EDIT: The data cannot be read with loadtxt().

So I do it like this:

data = array([])
for frame in frames:
    # ....
    # get some lines and make some calculations e.g. final result is
    # line = array([1, 2, 3, 4])
    # ....
    if data.size == 0:
        data = line
    else:
        data = vstack( (data, line) )

This works fine, but the if-clausel make the solution just look ugly. I wonder if there is a possibility to get ride of it.

Any ideas?

5
  • 2
    docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html ? Commented Dec 5, 2012 at 13:11
  • 1
    Using data = vstack((data, line)) if data else line? Commented Dec 5, 2012 at 13:13
  • @Bakuriu The truth value of an array with more than one element is ambiguous. Maybe: data = vstack((data, line)) if data.size else line. Looks better, but still with the same issue of the "if". Commented Dec 5, 2012 at 13:18
  • It is better to first append to a list and then use np.concatenate (or its specialized derivatives) for speed reasons. Commented Dec 5, 2012 at 13:26
  • For the vstack problem itself, the solution is to use data = np.empty((0,4)), but using a temporary list is probably better (or best you already know the arrays size and just fill it) Commented Dec 5, 2012 at 13:48

1 Answer 1

1

If the number of elements in line is fixed and you just want to avoid an "ugly" solution, you can do this:

data = []
for f in frames:
    # do your calculation
    # line = [1, 2, 3, 4]
    data += line
data = np.array(data).reshape((-1,4))
Sign up to request clarification or add additional context in comments.

1 Comment

Yes exactly! This is a "beautiful" solution. ^^

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.