Home > other >  Saving data in Python
Saving data in Python

Time:05-04

I am trying to save the data in a CSV format. The current and desired outputs are attached.

import numpy as np
import csv

r = np.linspace(0, 100e-6, 5)
A=np.array([[23.9496871440374 - 1336167292.56833*r**2],
       [21.986288555672 - 1373636804.80965*r**2]])

with open('Vel_Profiles.csv', 'w') as f:
    writer = csv.writer(f)

    writer.writerows((r,A))

The current output is

enter image description here

The desired output is

Output

CodePudding user response:

Here is what worked for me to get your expected output:

import numpy as np
import csv

r = np.linspace(0, 100e-6, 5)
A=np.array([[23.9496871440374 - 1336167292.56833*r**2],
       [21.986288555672 - 1373636804.80965*r**2]])

out = np.vstack([r,A.squeeze()]).T
np.savetxt('Vel_Profiles.csv', out, delimiter=',', fmt=['%2.2E', '%.5f', '%.6f'])

output:
0.00E 00    23.94969    21.986289
2.50E-05    23.11458    21.127766
5.00E-05    20.60927    18.552197
7.50E-05    16.43375    14.259582
1.00E-04    10.58801    8.249921

UPDATE Specifying the format of all columns in a more general way like asked in the comments

r = np.linspace(0, 100e-6, 5)
A=np.array([[23.9496871440374 - 1336167292.56833*r**2],
       [21.986288555672 - 1373636804.80965*r**2]])
out = np.vstack([r,A.squeeze()]).T

test = np.hstack([out,out,out])
print(test.shape)
# (5, 9)

# build list of same len than shape[1] with format
# here , we would have 3 times the same data next to each other so just multiply it by 3
my_format = ['%2.2E', '%.5f', '%.6f']
my_list_of_formats = my_format*3
# ['%2.2E', '%.5f', '%.6f', '%2.2E', '%.5f', '%.6f', '%2.2E', '%.5f', '%.6f']

#or like this:
my_list_of_formats = [my_format[i % 3] for i in range(test.shape[1])]
# ['%2.2E', '%.5f', '%.6f', '%2.2E', '%.5f', '%.6f', '%2.2E', '%.5f', '%.6f']

np.savetxt('Vel_Profiles.csv', test, delimiter=',', fmt=my_list_of_formats)

you can also specify just one format like '%2.2E' to fmt=, then every column gets formatted that way

CodePudding user response:

You don't need to use another library, you can use Numpy itself.

You can do this:

import numpy as np
np.savetxt('file_name.csv', your_array, delimiter=',')

If you need to stack your arrays first you can do something like this first:

array = np.vstack([r, A])

Check out the documentation here:

savetxt: https://numpy.org/doc/stable/reference/generated/numpy.savetxt.html

vstack: https://numpy.org/doc/stable/reference/generated/numpy.vstack.html

  • Related