指定字段名numpy的数组在Python 2.7.3 [英] Assigning field names to numpy array in Python 2.7.3

查看:1513
本文介绍了指定字段名numpy的数组在Python 2.7.3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这一个去坚果,因为我显然错过了点和解决方案过于简单看:(

我有x列的np.array,我想分配一个字段名。因此,这里是我的code:

 数据= np.array([1,2,3],[4.0,5.0,6.0],[11,12,12.3]])
A = np.array(数据,DTYPE = {'名':'1','第二','3'],格式:F8,F8,F8]})
打印['1']

为什么这给

  [1. 2. 3.]
 [4. 5. 6.]
 [11. 12. 12.3]

而不是 [1,2,3]


解决方案

 在[1]:数据= np.array([1,2,3],[4.0,5.0 ,6.0],[11,12,12.3]])
在[2]:DT = np.dtype({'名称':['第一','第二','3'],'格式':['F8','F8','F8']})

您尝试:

 在[3]:np.array(数据,DT)
出[3]:
阵列([[(1.0,1.0,1.0),(2.0,2.0,2.0),(3.0,3.0,3.0)]
       [(4.0,4.0,4.0),(5.0,5.0,5.0),(6.0,6.0,6.0)],
       [(11.0,11.0,11.0),(12.0,12.0,12.0),(12.3,12.3,12.3)]]
      DTYPE = [('第一','&所述; F8'),('第2','&所述; F8'),('3','&所述; F8')])

产生(3,3)阵列,与分配给每个字段相同的值。 data.astype(DT)做同样的事。

视图产生一个(3,1)数组,其中的每个字段包含一列中的数据。

  [4]:data.view(DT)
出[4]:
阵列([[(1.0,2.0,3.0)],
       [(4.0,5.0,6.0)]
       [(11.0,12.0,12.3)]]
      DTYPE = [('第一','&所述; F8'),('第2','&所述; F8'),('3','&所述; F8')])

我要警告说,如果所有字段具有相同的数据类型与原始视图才有效。它使用相同的数据缓冲区,只是间$ P $不同pting的值。

您可以从重塑(3,1)的结果(3)。

不过既然你想 A ['1'] [1,2,3] - 一个数据行 - 我们必须做一些其他的操作。

 在[16]:data.T.copy()视图(DT)
出[16]:
阵列([[(1.0,4.0,11.0)]
       [(2.0,5.0,12.0)]
       [(3.0,6.0,12.3)]]
      DTYPE = [('第一','&所述; F8'),('第2','&所述; F8'),('3','&所述; F8')])
在[17]:_ ['1']
出[17]:
阵列([[1],
       [2.],
       [3.]])

我转,然后进行复印(重新整理基础数据缓冲区)。现在视图看跌 [1,2,3] 中的一个字段。

请注意,该结构化阵列使用的显示()而不是 [] 为行。这是线索,它是如何接受输入。

我可以把你的数据成元组的一个列表:

  [19]:[元组data.T(i)就我]
出[19]:[(1.0,4.0,11.0),(2.0,5.0,12.0),(3.0,6.0,12.300000000000001)]在[20]:np.array([元组(i)在我data.T],DT)
出[20]:
阵列([(1.0,4.0,11.0),(2.0,5.0,12.0),(3.0,6.0,12.3)],
      DTYPE = [('第一','&所述; F8'),('第2','&所述; F8'),('3','&所述; F8')])
在[21]:_ ['1']
出[21]:阵列([1,2,3])

这是一个(3)阵列3场。

的元组的名单提供的数据 np.array(...,DT)的正常方式。查看文档链接在我的评论。

您还可以创建一个空数组,并填写,通过现场按行或字段行

 在[26]:A = np.zeros((3),DT)
在[27]:因为我在范围内(3):
   ....:A [i] =数据[:,我] .copy()

如果没有复制我收到了 ValueError错误:ndarray不是C连续

通过现场填写领域:

 在[29]:因为我在范围(3):
   ....:A [dt.names [I] =数据[一世:]

一般结构化阵列具有多行和一些字段。因此,通过现场填写是比较快的。这是 recarray 功能如何处理最复印任务。


fromiter 也可以用:

 在[31]:np.fromiter(数据,DTYPE = DT)
出[31]:
阵列([(1.0,2.0,3.0),(4.0,5.0,6.0),(11.0,12.0,12.3)],
     DTYPE = [('第一','&所述; F8'),('第2','&所述; F8'),('3','&所述; F8')])

但是,错误使用,当我得到 data.T 无副本是受行迭代做该行强大的指示(我在文献[27])

 在[32]:np.fromiter(data.T,DTYPE = DT)
  ValueError错误:ndarray不是C连续

拉链(*数据)是重新排序输入数组(见注释 @ unutbu的答案的另一种方式链接)。

  np.fromiter(邮政编码(*数据),DTYPE = DT)

正如评论指出的那样, fromarrays

  np.rec.fromarrays(数据,DT)

这是使用通过现场复制方法的录制函数的例子:

 的ArrayList = [在ArrayList的点¯xsb.asarray(X)]
....
_array = recarray(形状,DESCR)
#填充记录阵列(使复印件)
因为我在范围内(LEN(ArrayList中)):
    _array [_names [I] = ArrayList的[I]

在我们的例子是:

  [8]:[数据np.asarray(i)就我]数据1 =
在[9]:DATA1
出[9]:[阵列([1,2,3]),阵列([4,5,6]),阵列([11,12,12.3])]
在[10]:因为我在范围内(3):
    A [dt.names [I] = DATA1 [I]

I am going nuts over this one, as I obviously miss the point and the solution is too simple to see :(

I have an np.array with x columns, and I want to assign a field name. So here is my code:

data = np.array([[1,2,3], [4.0,5.0,6.0], [11,12,12.3]])
a = np.array(data, dtype= {'names': ['1st', '2nd', '3rd'], 'formats':['f8','f8', 'f8']})
print a['1st']

why does this give

[[  1.    2.    3. ]
 [  4.    5.    6. ]
 [ 11.   12.   12.3]]

Instead of [1, 2, 3]?

解决方案

In [1]: data = np.array([[1,2,3], [4.0,5.0,6.0], [11,12,12.3]])
In [2]: dt = np.dtype({'names': ['1st', '2nd', '3rd'], 'formats':['f8','f8', 'f8']})

Your attempt:

In [3]: np.array(data,dt)
Out[3]: 
array([[(1.0, 1.0, 1.0), (2.0, 2.0, 2.0), (3.0, 3.0, 3.0)],
       [(4.0, 4.0, 4.0), (5.0, 5.0, 5.0), (6.0, 6.0, 6.0)],
       [(11.0, 11.0, 11.0), (12.0, 12.0, 12.0), (12.3, 12.3, 12.3)]], 
      dtype=[('1st', '<f8'), ('2nd', '<f8'), ('3rd', '<f8')])

produces a (3,3) array, with the same values assigned to each field. data.astype(dt) does the same thing.

But view produces a (3,1) array in which each field contains the data for a column.

In [4]: data.view(dt)
Out[4]: 
array([[(1.0, 2.0, 3.0)],
       [(4.0, 5.0, 6.0)],
       [(11.0, 12.0, 12.3)]], 
      dtype=[('1st', '<f8'), ('2nd', '<f8'), ('3rd', '<f8')])

I should caution that view only works if all the fields have the same data type as the original. It uses the same data buffer, just interpreting the values differently.

You could reshape the result from (3,1) to (3,).

But since you want A['1st'] to be [1,2,3] - a row of data - we have to do some other manipulation.

In [16]: data.T.copy().view(dt)
Out[16]: 
array([[(1.0, 4.0, 11.0)],
       [(2.0, 5.0, 12.0)],
       [(3.0, 6.0, 12.3)]], 
      dtype=[('1st', '<f8'), ('2nd', '<f8'), ('3rd', '<f8')])
In [17]: _['1st']
Out[17]: 
array([[ 1.],
       [ 2.],
       [ 3.]])

I transpose, and then make a copy (rearranging the underlying data buffer). Now a view puts [1,2,3] in one field.

Note that the display of the structured array uses () instead of [] for the 'rows'. This is clue as to how it accepts input.

I can turn your data into a list of tuples with:

In [19]: [tuple(i) for i in data.T]
Out[19]: [(1.0, 4.0, 11.0), (2.0, 5.0, 12.0), (3.0, 6.0, 12.300000000000001)]

In [20]: np.array([tuple(i) for i in data.T],dt)
Out[20]: 
array([(1.0, 4.0, 11.0), (2.0, 5.0, 12.0), (3.0, 6.0, 12.3)], 
      dtype=[('1st', '<f8'), ('2nd', '<f8'), ('3rd', '<f8')])
In [21]: _['1st']
Out[21]: array([ 1.,  2.,  3.])

This is a (3,) array with 3 fields.

A list of tuples is the normal way of supplying data to np.array(...,dt). See the doc link in my comment.

You can also create an empty array, and fill it, row by row, or field by field

In [26]: A=np.zeros((3,),dt)
In [27]: for i in range(3):
   ....:     A[i]=data[:,i].copy()

Without the copy I get a ValueError: ndarray is not C-contiguous

Fill field by field:

In [29]: for i in range(3):
   ....:     A[dt.names[i]]=data[i,:]

Usually a structured array has many rows, and a few fields. So filling by field is relatively fast. That's how recarray functions handle most copying tasks.


fromiter can also be used:

In [31]: np.fromiter(data, dtype=dt)
Out[31]: 
array([(1.0, 2.0, 3.0), (4.0, 5.0, 6.0), (11.0, 12.0, 12.3)], 
     dtype=[('1st', '<f8'), ('2nd', '<f8'), ('3rd', '<f8')])

But the error I get when using data.T without the copy is a strong indication that is doing the row by row iteration (my In[27])

In [32]: np.fromiter(data.T, dtype=dt)
  ValueError: ndarray is not C-contiguous

zip(*data) is another way of reordering the input array (see @unutbu's answer in the comment link).

np.fromiter(zip(*data),dtype=dt)

As pointed out in a comment, fromarrays works:

np.rec.fromarrays(data,dt)

This is an example of a rec function that uses the by field copy method:

arrayList = [sb.asarray(x) for x in arrayList]
....
_array = recarray(shape, descr)
# populate the record array (makes a copy)
for i in range(len(arrayList)):
    _array[_names[i]] = arrayList[i]

Which in our case is:

In [8]: data1 = [np.asarray(i) for i in data]
In [9]: data1
Out[9]: [array([ 1.,  2.,  3.]), array([ 4.,  5.,  6.]), array([ 11. ,  12. ,  12.3])]
In [10]: for i in range(3):
    A[dt.names[i]] = data1[i]

这篇关于指定字段名numpy的数组在Python 2.7.3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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