将多个记录重新分配给记录数组?

时间:2011-11-11 03:40:14

标签: python numpy

我想将转换应用于记录数组的某些列并重新分配这些值。这样做的规范方法是什么?

List = [['a',.3,.3],
        ['b',-.5,.4]]

Arr = np.rec.fromrecords(List,names=['id','var1','var2'])

我想对某些变量应用一些缩放。我会以此为例,但一般来说,缩放可能比减去均值更复杂。

scale = lambda x: x - x.mean(0)

这不起作用

Arr[['var1','var2']].mean(0)
TypeError: cannot perform reduce with flexible type

所以我必须首先转换为非结构化数组,但是如何重新分配回记录数组?我会循环吗?

Unstr = Arr[['var1','var2']].view('float').reshape(len(Arr),-1)

Arr[['var1','var2']] = scale(Unstr)

IndexError: unsupported iterator index

1 个答案:

答案 0 :(得分:1)

为什么不逐个扩展变量?

In [13]: %paste
import numpy as np

List = [['a',.3,.3],
        ['b',-.5,.4]]

scale = lambda x: x - x.mean()
Arr = np.rec.fromrecords(List,names=['id','var1','var2'])

vars_to_scale = ['var1', 'var2']
for var in vars_to_scale:
    Arr[var] = scale(Arr[var])
print Arr
## -- End pasted text --
[('a', 0.4, -0.04999999999999999) ('b', -0.4, 0.050000000000000044)]