使用混合数据保存numpy数组

使用混合数据保存numpy数组

本文介绍了使用混合数据保存numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个numpy数组,其中每个值都是一个浮点后跟一个整数,例如:

I have a numpy array where every value is a float followed by an integer, e.g.:

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

我会喜欢这样保存:

0.4324321 0 0.9437212 1 0.4738721 0 0.49327321 0

但如果我打电话:

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

我得到了错误:

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

我该如何解决这个问题?

How can I fix this?

推荐答案

你真正的问题是打印出1D 8元素数组会给你8行1列(或者,如果你强行,1行8列), 4行2列。因此,您只能指定一种格式(或者,如果你强制使用1或8种格式)。

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. So, you can only specify a single format (or, if you force things, either 1 or 8 formats).

如果你想以4x2的形状输出它1x8,你需要先重塑数组:

If you want to output this in a 4x2 shape instead of 1x8, you need to reshape the array first:

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

这将给你:

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

如果你想把它写成1行8列,首先需要将它重新整形为1行8列而不是8行。

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.

然后你需要指定8种格式。没有办法告诉numpy重复这两种格式四次,但如果没有numpy的帮助,这很容易做到:

And then you need to specify 8 formats. 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.savetxt('output.dat', my_array.reshape((1,8)), fmt='%f %i ' * 4)

这给你:

0.432432 0 0.943721 1 0.473872 0 0.493273 0

这篇关于使用混合数据保存numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 00:42