(我读的太快了,错过了 A 一个整数数组。下面可能有点过头了,但我会留在这里,以防有人需要混合字符串和浮点数。)
如果数组是相同的数据类型,您可以将它们连接起来,savetxt 就可以正常工作。如果A 是一个字符串数组,那将不起作用。要让savetxt 将此异构数据打印到文件中,您需要使用structured array。这是一种方法。
这个想法是创建一个结构化数组,其第一个字段是一个字符串
(保存ID),其剩余的M个字段是浮点数。
为了方便用给定的数组填充这个数组,我们将这样做
分两步。
首先,我们将创建一个结构化数组,其第一个字段是字符串
并且其第二个字段本身就是一个 M 个浮点值的数组。
这个数据类型在脚本中是dt2,对应的数组是
data2。这允许我们使用 a 和 b 填充数组
简单的赋值 data2['a'] = a 和 data2['b'] = b。
接下来我们为这个数组创建一个视图,在脚本中称为data,
使用数据类型 dtall 和 M+1 字段。第一个字段是
字符串,其余为浮点数。
现在我们可以使用savetxt 将data 写入文件。提供格式
对于与其他字段不同的第一个字段,我们将构建一个
整行的完整格式字符串,并将其作为fmt
savetxt的参数。
import numpy as np
# Example data.
a = np.array(['A001', 'A019', 'A344', 'A742'])
b = np.linspace(0, 1, 16, endpoint=False).reshape(4,4)
# Create a data dtype with two fields. The first field has the same
# data type as `a`. The second has the same fundamental data type as `b`,
# repeated N times. If you print dt2 using the above data, you'll see
# [('a', 'S4'), ('b', '<f8', (4,))]
dt2 = np.dtype([('a', a.dtype.str)] +
[('b', b.dtype.str, b.shape[1])])
# Create an empty array using `dt2`, and fill it with `a` and `b`.
data2 = np.empty(len(a), dtype=dt2)
data2['a'] = a
data2['b'] = b
# Create a data type with N+1 fields. If you print `dtall`, you'll see
# [('a', 'S4'), ('f1', '<f8'), ('f2', '<f8'), ('f3', '<f8'), ('f4', '<f8')]
dtall = np.dtype([('a', a.dtype.str)] + b.dtype.descr*b.shape[1])
# Create a view of the same data, but with data type `dtall`.
data = data2.view(dtall)
# Create the format string to be used in `savetxt`.
id_fmt = '"%s"' # The format of the id.
float_fmt = '%f' # The floating point format.
fmt = id_fmt + b.shape[1] * (',' + float_fmt)
# Finally, save the data.
np.savetxt('ab.csv', data, fmt=fmt)
这是输出文件的内容:
"A001",0.000000,0.062500,0.125000,0.187500
"A019",0.250000,0.312500,0.375000,0.437500
"A344",0.500000,0.562500,0.625000,0.687500
"A742",0.750000,0.812500,0.875000,0.937500