正在 Python 中保存数据

Saving data in Python

我正在尝试以 CSV 格式保存数据。附上当前和所需的输出。

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))

当前输出为

期望的输出是

你不需要使用其他库,你可以使用 Numpy 本身。

你可以这样做:

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

如果你需要先堆叠你的阵列,你可以先做这样的事情:

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

在此处查看文档:

保存文本:https://numpy.org/doc/stable/reference/generated/numpy.savetxt.html

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

以下是我获得预期输出的方法:

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

更新 以评论中要求的更通用的方式指定所有列的格式

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)

您也可以只指定一种格式,例如 '%2.2E'fmt=,然后每列都以这种方式设置格式