2013-01-20 18 views
7

我是python的新手,所以這可能聽起來很基本。我已經使用csv2rec導入了一個csv文件。第一行有標題。我想將標題更改爲'x','y','z'。這樣做的最好方法是什麼?我可以重命名字段在一個numpy記錄陣列

>>> import matplotlib 
>>> import matplotlib.mlab as mlab 
>>> r= mlab.csv2rec('HeightWeight.csv', delimiter= ',') 
>>> names= r.dtype.names 
>>> for i in names: 
    print i 


index 
heightinches 
weightpounds 

回答

2

mlab.csv2recnames參數,你可以用它來設置列名:

r= mlab.csv2rec('HeightWeight.csv', delimiter= ',', 
       names=['apple', 'pear'], 
       skiprows=1) 

names不是None時,csv2rec假定沒有標題行。因此,使用skiprows=1來忽略標題行。

+0

+1應用相同的重命名操作 - 甚至更好。 – DSM

20

你可以簡單地分配給.dtype.names

>>> d = np.array([(1.0, 2), (3.0, 4)], dtype=[('a', float), ('b', int)]) 
>>> d 
array([(1.0, 2), (3.0, 4)], 
     dtype=[('a', '<f8'), ('b', '<i8')]) 
>>> d['a'] 
array([ 1., 3.]) 
>>> d.dtype.names 
('a', 'b') 
>>> d.dtype.names = 'x', 'y' 
>>> d 
array([(1.0, 2), (3.0, 4)], 
     dtype=[('x', '<f8'), ('y', '<i8')]) 
>>> d['x'] 
array([ 1., 3.]) 

同樣的方式與recarray

>>> d 
rec.array([(1.0, 2), (3.0, 4)], 
     dtype=[('a', '<f8'), ('b', '<i8')]) 
>>> d.dtype.names = 'apple', 'pear' 
>>> d 
rec.array([(1.0, 2), (3.0, 4)], 
     dtype=[('apple', '<f8'), ('pear', '<i8')]) 
+0

感謝。這有幫助。 – user1995519

+1

如果該數組是一個masked_array,那麼您將需要對'd.mask.dtype.names' – ccbunney

0

爲此,numpy.lib.recfunctions中有一個rename_fields方法。它也適用於被掩碼的數組。

import numpy as np 
import numpy.lib.recfunctions as rfn 

ab = np.ma.zeros(3, dtype=[('a', 'f4'), ('b', 'i4')]) 
xy = rfn.rename_fields(ab, {'a': 'x', 'b': 'y'}) 

print(ab.dtype, ab.mask.dtype) 
print(xy.dtype, xy.mask.dtype) 

輸出:

[('a', '<f4'), ('b', '<i4')] [('a', '?'), ('b', '?')] 
[('x', '<f4'), ('y', '<i4')] [('x', '?'), ('y', '?')]