Create two 2D numpy arrays from a list of strings

I have a list of lines in the form:

"a, b, c, d, e ... z,"

Where the first x should be saved as a string in one 2D array, and the rest of the string is saved as a string in another two-dimensional array.

Now, if it was in C / C ++ or Java, that would be easy, and I could do it in a few seconds. But I have not used 100% on python yet. But given, for example, an array like:

['1, 2, 4, 5,', '2, 3, 6, 3,', '1, 1, 7, 6']

and said that they should be divided into 2 columns in the first array, two in the second array, as if I would flip this list into the following two numpy arrays:

[[1, 2]
 [2, 3]
 [1, 1]]

and

[[4, 5]
 [6, 3]
 [7, 6]]

Also for my own understanding of why this I cannot / should not go through each element in a nested loop and overwrite them one by one. I don’t understand why, when I try, so that the values ​​do not match what is copied.

, :

    self.inputs=np.zeros((len(data), self.numIn))
    self.outputs=np.zeros((len(data),self.numOut))
    lineIndex=0
    for line in data:
        d=line.split(',')

        for i in range(self.numIn):
            self.inputs[lineIndex][i]=d[i]
            print d[i],
            self.inputs.index()
        for j in range(self.numOut):
            self.inputs[lineIndex][j]=d[self.numIn+j]
        lineIndex+=1

, python/numpy numpy , . , . ( !: P)

+2
1

:

, python/numpy numpy , . , . ( !: P)

strip ( ) split ( ) ,

a = ['1, 2, 4, 5,', '2, 3, 6, 3,', '1, 1, 7, 6']
rows = [l.rstrip(',').split(',') for l in a]
rows
#[['1', ' 2', ' 4', ' 5'], ['2', ' 3', ' 6', ' 3'], ['1', ' 1', ' 7', ' 6']]

:

arr = np.array(rows, int)

arr
#array([[1, 2, 4, 5],
#       [2, 3, 6, 3],
#       [1, 1, 7, 6]])

:

arr[:, :2] # first two columns
#array([[1, 2],
#       [2, 3],
#       [1, 1]])

arr[:, -2:] # last two columns
#array([[4, 5],
#       [6, 3],
#       [7, 6]])

, :

a, b = np.split(arr, arr.shape[1]/2, axis=1)
+3

Source: https://habr.com/ru/post/1662566/


All Articles