numpy错误中的掩码数组

时间:2011-04-18 23:49:11

标签: python arrays numpy recarray

我使用genfromtxt输入了一个文件,但是有些值丢失了,所以我生成了一个蒙版数组。当我尝试索引屏蔽数组的某些记录值时,我得到一个我无法弄清楚的错误。任何帮助将受到高度赞赏。谢谢。 --Alex

import csv
import datetime
import time
import numpy as np
import numpy.lib.recfunctions as rf
import pprint
import numpy.ma as ma

date_converter = lambda x: datetime.date(int(x[-4:]), int(x[3:5]), int(x[:2]))
input_file = np.genfromtxt("../data/test.csv", usemask=True, converters={0:date_converter}, dtype="O4, i8, i8, i8, i8", names="date, firm, val1, val2, val3", delimiter=",", skip_header=1)

生成:

masked_array(data = [(datetime.date(2001, 3, 1), 1L, --, 14L, 15L)
 (datetime.date(2001, 2, 1), 1L, 10L, 11L, 12L)
 (datetime.date(2001, 5, 1), 1L, 19L, 20L, 21L)
 (datetime.date(2001, 4, 1), 1L, 16L, --, 18L)],
             mask = [(False, False, True, False, False) (False, False, False, False, False)
 (False, False, False, False, False) (False, False, False, True, False)],
       fill_value = ('?', 999999L, 999999L, 999999L, 999999L),
            dtype = [('date', '|O4'), ('firm', '<i8'), ('val1', '<i8'), ('val2', '<i8'), ('val3', '<i8')])

当我运行input_file[0]时,我收到以下错误:

Traceback (most recent call last):
  File "<pyshell#278>", line 1, in <module>
    input_file[0]
  File "C:\Python27\lib\site-packages\numpy\ma\core.py", line 2956, in __getitem__
    dout = mvoid(dout, mask=mask)
  File "C:\Python27\lib\site-packages\numpy\ma\core.py", line 5529, in __new__
    _data[()] = data
ValueError: Setting void-array with object members using buffer.

1 个答案:

答案 0 :(得分:0)

input_file [0]不是访问掩码数组中数据的正确方法(参见documentation

例如:

>>> import numpy as np
>>> arr = np.ma.ones(3, dtype=[('c1', np.int),('c2', np.int)])
>>> arr.mask[0][1] = True
>>> arr.data[0][0] = 2              
>>> np.ma.getdata(arr)[1][0] = 3    
>>> arr.data[2][0] = 4       
>>> print(arr)
   [(2, --) (3, 1) (4, 1)]