使用带有标题的 np.savetxt 保存结构化的 numpy 数组 [英] Save structured numpy array using np.savetxt with header

查看:103
本文介绍了使用带有标题的 np.savetxt 保存结构化的 numpy 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个

output = np.zeros(names.size, dtype=[('name', 'U32'), ('r', float),('m',float)])

然后我尝试使用 np.savetxt 将其保存到 csv 文件中.我想知道是否有办法将每列的标签保存为 csv 文件的标题?

Then I tried to save it into a csv file using np.savetxt. I am wondering if there is way I could also save the label of each column as the header of the csv file?

提前致谢.

推荐答案

您可以尝试类似于 this SO answer 透视数据

You could try a solution similar to this SO answer to pivot the data

dtypes = [('name', 'U32'), ('r', float),('m',float)]
a = np.zeros(5, dtype=dtypes)
b = numpy.vstack(map(list, a))

将列表映射到 recarray 元组,然后垂直堆叠它们.

Where you map list over the recarray tuples, and then vertically stack them.

然后你可以做以下...

Then you can do the following...

names = [n for n, t in dtypes]
numpy.savetxt('test.csv', b, header=','.join(names), fmt=','.join(['%s']*b.shape[1]))

这篇关于使用带有标题的 np.savetxt 保存结构化的 numpy 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆