简体   繁体   English

使用混合数据保存numpy数组

[英]Saving a numpy array with mixed data

I have a numpy array where every value is a float followed by an integer, eg: 我有一个numpy数组,其中每个值都是一个浮点后跟一个整数,例如:

my_array = numpy.array([0.4324321, 0, 0.9437212, 1, 0.4738721, 0, 0.49327321, 0])

I would like to save it like this: 我想像这样保存它:

0.4324321 0 0.9437212 1 0.4738721 0 0.49327321 0

But if I call: 但如果我打电话:

numpy.savetxt('output.dat',my_array,fmt='%f %i')

I get an error: 我收到一个错误:

AttributeError: fmt has wrong number of % formats.  %f %i

How can I fix this? 我怎样才能解决这个问题?

Your real problem is that printing out a 1D 8-element array gives you 8 rows of 1 column (or, if you force things, 1 row of 8 columns), not 4 rows of 2 columns. 你真正的问题是打印出1D 8元素数组会给你8行1列(或者,如果强行,1行8列),而不是4行2列。 So, you can only specify a single format (or, if you force things, either 1 or 8 formats). 因此,您只能指定一种格式(或者,如果您强制使用1或8种格式)。

If you want to output this in a 4x2 shape instead of 1x8, you need to reshape the array first: 如果要以4x2形状而不是1x8输出,则需要先重新整形数组:

numpy.savetxt('output.dat', my_array.reshape((4,2)), fmt='%f %i')

This will give you: 这会给你:

0.432432 0
0.943721 1
0.473872 0
0.493273 0

The docs are a little confusing, as they devote most of the wording to dealing with complex numbers instead of simple floats and ints, but the basic rules are the same. 文档有点令人困惑,因为他们将大部分措辞用于处理复杂的数字而不是简单的浮点数和整数,但基本规则是相同的。 You specify either a single specifier, or a specifier for each column (the in-between case of specifying real and imaginary parts for each column isn't relevant). 您为每列指定单个说明符或说明符(指定每列的实部和虚部的中间情况不相关)。


If you want to write it in 1 row of 8 columns, first you need to reshape it into something with 1 row of 8 columns instead of 8 rows. 如果要将其写入1行8列中,首先需要将其重新整形为1行8列而不是8行。

And then you need to specify 8 formats. 然后你需要指定8种格式。 There's no way to tell numpy "repeat these two formats four times", but that's pretty easy to do without numpy's help: 没有办法告诉numpy“重复这两种格式四次”,但如果没有numpy的帮助,这很容易做到:

numpy.savetxt('output.dat', my_array.reshape((1,8)), fmt='%f %i ' * 4)

And that gives you: 这会给你:

0.432432 0 0.943721 1 0.473872 0 0.493273 0 

The problem is that savetxt() will print one row for each array entry. 问题是savetxt()将为每个数组条目打印一行。 You can force a 2D-array creating a new axis and then print the (1x8) format: 您可以强制2D-array创建新轴,然后打印(1x8)格式:

numpy.savetxt('output.dat', my_array[numpy.newaxis,:], fmt='%f %i'*4)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM