-1

So i want to read two 2D-arrays A and B from a csv file as a numpy-Array
i have the following csv file with ";" seperating two arrays:

A;B  
1,1,2,2;3,3,4,4  
6,7,3,7;3,5,3,5  
1,8,5,3;6,1,7,5  

The result should be something like this

A = [[1, 1, 2, 2], [6, 7, 3, 7], [1, 8, 5, 3]]   
B = [[3, 3, 4, 4], [3, 7, 3, 7], [6, 1, 7, 5]]  

now how i am supposed to do it, i tried alot with loadtxt and genfromtxt but couldn't do it

RainBat
  • 33
  • 4
  • 2
    Where is this coming from? That's a weird serialization to begin with. The sample you give isn't even consistent with delimiter usage. Please see: [What is the XY problem?](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) – EJoshuaS - Stand with Ukraine Nov 18 '19 at 22:50
  • believe it or not, it's a university question. we were only taught numpy.loadtxt and numpy.savetxt – RainBat Nov 18 '19 at 22:52
  • I assume that you're supposed to use the `;` as the delimiter for the initial load to split the CSV into columns, and then split again on the `,` – EJoshuaS - Stand with Ukraine Nov 18 '19 at 22:55
  • [This](https://stackoverflow.com/questions/3518778/how-do-i-read-csv-data-into-a-record-array-in-numpy) could be a good place to start I guess. – EJoshuaS - Stand with Ukraine Nov 18 '19 at 22:58
  • “I tried alot with...” What did you try, exactly? It might be useful to share your attempts and some explanations. – AMC Nov 19 '19 at 04:24

2 Answers2

1

Have you tried csv? I'm not posting the whole code, but something like this:

import csv

with open('fileName.csv') as file:
    csv_reader =  csv.reader(file, delimiter=',')
    for row in csv_reader:
        #do sth
emsiiggy
  • 343
  • 1
  • 2
  • 13
0

This should work, there may be a more numpy way, but this is how i made the array:

import numpy as np
import pandas as pd
A=[]
B=[]
df1=pd.read_csv('numpy.csv', sep=";") 
for x in range(len(df1.A)):
   A.append(df1.A[x].split(','))
for x in range(len(df1.B)):
   B.append(df1.B[x].split(','))
A=np.array(A).astype(np.int)
B=np.array(B).astype(np.int)

A
#array([[1, 1, 2, 2],
#       [6, 7, 3, 7],
#       [1, 8, 5, 3]])

B
Out[251]: 
#array([[3, 3, 4, 4],
#       [3, 5, 3, 5],
#       [6, 1, 7, 5]])
oppressionslayer
  • 6,942
  • 2
  • 7
  • 24