开发者

How to save a mix of strings and numbers into text files in specified format using numpy.savetxt?

with one array of strings and the other array of numbers, like

str_arr = np.array(['object1_short', 'object2_intermidiate', 'object3_long'])

and

flt_arr = np.arra开发者_高级运维y([10.01234235, 11.01234235, 12.023432])

How can I specified fmt in np.savetxt so that the text file will be

object1    10.01
object2    11.01
object3    12.02

, i.e., two arrays in %7s and %4.2f respectively.

I really want to use numpy.savetxt to do this, but directly specifying

np.savetxt("output.txt", np.vstack([str_arr, flt_arr]).T), fmt = '%7s %4.2f')

seems doesnot work. Is it doable with savetxt at all? I really prefer a numpy.array based solution rather than going for spliting and reformating using list comprehensions, or recarrays.

Thanks.


You can't make an ndarray of nonhomogeneous array types, so stacking str_arr and flt_arr won't work. You could start by converting flt_arr into an array of strs doing something like this:

>>> np.char.mod("%4.2f", flt_arr)
array(['10.01', '11.01', '12.02'], 
      dtype='|S5')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜