0

data = [[1 2 3 4][5 6 7 8][9 10 11 12]]

The object I receive has this structure. The numbers in each sub-array aren't separated

I've tried to convert into a list and then split it but it writes separated rows

simMatrix = open(ficheroDestino, 'w', newline='') with simMatrix: writer = csv.writer(simMatrix,delimiter=',') for x in range (0,len(data)): result = data[x].tolist() writer.writerow(result)

Other code:

                                 simMatrix = open(ficheroDestino, 'w',newline='')
                                 with simMatrix:
                                 writer = csv.writer(simMatrix,delimiter=',')
                                 for x in range (0,len(data)):
                                     result = data[x].tolist()
                                     result2 = ' '.join(str(e) for e in datos)
                                     result3 = datos2.split(" ")
                                     writer.writerow(result3)

I expect the output of my csv as: 1 2 3 4

5 6 7 8

8 10 11 12

each number in a different column and row

2
  • what do you mean by the numbers in each sub-array aren't separated. What's the shape of data array ? Commented Sep 5, 2019 at 23:46
  • its just one item like [1 2 3 4 ] for example: data[0] = [1 2 3 4] as one item, I want to separate this numbers llike [1, 2, 3, 4] and write it in a csv Commented Sep 5, 2019 at 23:49

3 Answers 3

1

I would use Pandas DataFrame to_csv method. Following is a sample

import numpy as np
import pandas as pd

data = [["1 2 3 4"], ["5 6 7 8"], ["9 10 11 12"]]
pd.DataFrame(np.array([str(i).replace("['", "").replace("']", "").split(" ") for i in data])).to_csv("file.csv")

Sign up to request clarification or add additional context in comments.

Comments

1

You can just try numpy.savetxt(), example code is as below:

import numpy as np

data = np.array([[1, 2, 3, 4],
                 [5, 6, 7, 8],
                 [9, 10, 11, 12]]).astype(int)

np.savetxt('test.csv', data, fmt='%d', delimiter=' ')

The .csv file will be like:

1 2 3 4
5 6 7 8
9 10 11 12

Comments

0

How about this.

    import pandas as pd
    data = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
    datas = pd.DataFrame(data)

    print(datas)
    datas.to_csv('./test.csv',index=False)

1 Comment

i tried this and it writes all in the first column for the row 1, for example row 1 and column 2 its empty

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.