Search code examples
pythonarraysnumpywhile-loopraw-input

Concatanating array by While on Python


I had some question on python,

I am trying to write something, where after each raw-input , I should input into program some data (with array form). Then this data (arrays 2 dimensioanl ) should be added to the other 2 D array Full of zeros. Then when I input the second data (it should be again changed to 2 D array) and must be added to array Which already contain the array with Zeros and array from input). And so , after each input , array should be added already created arrays. Here is the code.

from numpy import *

var=zeros(shape=(1,11)) #making 2D array with zeros

while True: 

    file=raw_input("write data file name or path")

    c=open(file, 'r')
    ArrayStr=loadtxt(c, dtype='S',) #making array

    var=vstack((ArrayStr, var)) # concatantaing array 
print var

So finally I am getting array, which have only 2 arrays concatanatted (arrays with zeros and last inputted data array)

Thanks for attention and help


Solution

  • Working code

    in1.txt

    ATOM
    1
    C1
    POS
    X
    1
    16.774
    117.860
    10.374
    1.00
    0.00
    

    in2.txt

    ATOM
    2
    C2
    POS
    X
    2
    18.774
    17.860
    30.374
    2.00
    0.00
    

    Code

    import numpy
    
    zeros = numpy.zeros(shape=(1,11)) #making 2D array with zeros
    
    var = None
    
    for i in range(1, 3):
        i1 = open("in" + str(i) + ".txt")
    
        a = numpy.loadtxt(i1, dtype='S')
    
        if var is None:
            var = numpy.vstack((a, zeros))
        else:
            var = numpy.vstack((var, a, zeros))
    
    print var
    

    Output

    >>> 
    [['ATOM' '1' 'C1' 'POS' 'X' '1' '16.774' '117.860' '10.374' '1.00' '0.00']
     ['0.0' '0.0' '0.0' '0.0' '0.0' '0.0' '0.0' '0.0' '0.0' '0.0' '0.0']
     ['ATOM' '2' 'C2' 'POS' 'X' '2' '18.774' '17.860' '30.374' '2.00' '0.00']
     ['0.0' '0.0' '0.0' '0.0' '0.0' '0.0' '0.0' '0.0' '0.0' '0.0' '0.0']]
    >>>