in the code below, my intention is to copy the rows of this matrix to a csv file. I know that the csv function writer copies an array perfectly. But when the row comes from a matrix this doesn't seem to work. The csv file then looks like this 'unwanted csv-file'. The numbers of one row are together in 1 place of the csv file. Each one on a separate row though, which is what I desired. But I need the numbers of 1 row seperated with commas.
This code is a simplification of the code needed for a simulation program. In which I want to copy the first row of a calculated matrix per time interval to a csv file. i in this example is replaced by time t and so each time the first row is sent to file1, second row to file2 and so on. But when I can solve the problem for this code, I can solve it for my simulation program as well.
import numpy as np
import csv
import pandas as pd
V = np.matrix([[ 8.12500000e-03 4.12066060e-02j, -4.02435390e-18 9.30274988e-19j, -5.41422932e-18 4.03695160e-19j],
[-7.21532153e-18 7.93138177e-19j, 8.12500000e-03 4.12066060e-02j, -6.50521303e-18 4.33680869e-18j],
[-7.09036473e-18 5.11438288e-19j, -6.50521303e-18 4.33680869e-18j, 8.12500000e-03 4.12066060e-02j]])
path = 'C:/Users/Gebruiker/OneDrive/Documenten/'
for i in range(0,3):
if i ==0:
with open(path 'test12345678911.csv', mode='w', newline='') as voltage_file_a:
voltage_writer_a = csv.writer(voltage_file_a, delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL)
row = np.array(abs(V[i,:]))
voltage_writer_a.writerow(row)
else:
with open(path 'test12345678911.csv', mode = 'a', newline = '') as voltage_file_a:
voltage_writer_a = csv.writer(voltage_file_a, delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL)
row = np.array(abs(V[i,:]))
voltage_writer_a.writerow(row)
I tried to solve this with the step 'row = np.array...' but this doesn't help. Has someone an idea how to convert the row of the matrix to the csv file.
This code results in the following csv-file: unwanted csv-file
CodePudding user response:
Some Commands that may be useful in this solution:
np.matrix.ravel()
np.matrix.flatten()
np.matrix.tolist()
In your example, replace the np.matrix
with V
.