0

this is my script its having some problem. I just want to save tree variables a1, a2, a3 using numpy savetxt after vstacking them. Its working well when all the variables (a1, a2, a3) are found in the loop. It getting problems when ether one of them found to be empty. So, how it can be tackled. Any help will be appreciated.

a1, a2, a3 =[], [], [], 
for a in xfile_UH:
    print(a)
    d1=np.genfromtxt(a,  dtype=str, delimiter='', usecols=np.arange(0,10))
    l=d1[0,5]
    l1=d1[0,6]
    m=d1[1,4]
    n=d1[1,5]
    p=d1[1,6]
    r=d1[1,8]
    q=d1[1,9]   
    if l=='L':
     if m=='0':
      if n=='0':
       if p=='0':
        if q=='0':
         print(d1[0,0])
         a11, a12, a13, a14, a15=d1[0,6], d1[0,7],d1[0,4], d1[1,8], d1[2,8]
         z1=np.hstack([a11, a12, a13, a14, a15])
         a1.append(z1)
         print(z1)
    if l=='L':
     if m=='0':
      if n=='0':
       if p=='0':
        if q>'0':
         print(d1[0,0])
         a11, a12, a13, a14, a15=d1[0,6], d1[0,7],d1[0,4], d1[1,9], d1[2,9]
         z2=np.hstack([a11, a12, a13, a14, a15])
         a2.append(z2)
    if l=='L':
     if m=='0':
      if n=='0':
       if p>'0':
        if r>'0':
         if q=='0':
          print(d1[0,0])
          a11, a12, a13, a14, a15=d1[0,6], d1[0,7],d1[0,4], d1[1,8], d1[2,8]
          z3=np.hstack([a11, a12, a13, a14, a15])
          a3.append(z3)
    else:
        print('continue')
np.savetxt('output.txt', np.vstack([a1, a2, a3]), fmt='%s', delimiter=',')   `                                                                Error I found:     raise ValueError('all input arrays must have the same shape')
ValueError: all input arrays must have the same shape
>>>
user1717828
  • 7,122
  • 8
  • 34
  • 59

1 Answers1

0

from what I understand, your code works except in the cases in which NumPy would raise an exception. This is indeed expected, as it doesn't make sense for vstack to work with arrays of difference shape.

In the loop you should check that your individual arrays have the same shape. You can use

a1.shape == a2.shape

which will return True or False depending on the shape of the array. Or simply use exceptions to control what to do in case your arrays don't have the same shape.

Also, please, in order to make it easier to read, try to copy your code in separate blocks, instead of in a single line.

Dharman
  • 30,962
  • 25
  • 85
  • 135
agganz
  • 1
  • Thank you all for response and suggestions. If I use a1.shape == a2.shape, it shows some instructions like this : AttributeError: 'list' object has no attribute 'shape'. So here my question is there any other options to save a1, a2, a3 irrespective of shapes of them. – Chittaranjan Mahato Feb 26 '21 at 16:09