【问题标题】:How to create a numpy 2d array from database with null values如何从具有空值的数据库创建一个 numpy 2d 数组
【发布时间】:2013-10-10 02:17:32
【问题描述】:

我正在尝试使用可以通过 python 的列名访问的二维数组。 数据来自数据库,它可能有不同的类型和空值。 NoneType 不允许在元组中,所以我尝试用 np.nan 替换它们。

如果数据库中没有空值,则这段代码有效。但是,我的最终目标是拥有一个掩码数组,但我什至无法创建一个数组。

import MySQLdb
import numpy

connection = MySQLdb.connect(host=server, user=user, passwd=password, db=db)
cursor = connection.cursor()
cursor.execute(query)
results = list(cursor.fetchall())

dt = [('cig', int), ('u_CIG', 'S10'), ('e_ICO', float), ('VCO', int)]

for index_r, row in enumerate(results):
    newrow = list(row)
    for index_c, col in enumerate(newrow):
        if col is None:
            newrow[index_c] = numpy.nan
    results[index_r] = tuple(newrow)
 x = numpy.array(results, dtype=dt)

产生的错误是:

x = numpy.array(results, dtype=dtypes)
ValueError: cannot convert float NaN to integer

执行 fetchall 后,结果包含如下内容:

[(10L,
'*',
Decimal('3.47'),
180L),
(27L,
' ',
Decimal('7.21'),
None)]

知道如何解决这个问题吗?谢谢!

【问题讨论】:

    标签: python arrays numpy nonetype


    【解决方案1】:

    以 Larsmans 为例,我认为您想要的是:

        import numpy as np
        import numpy.ma as ma
    
        values = [('<', 2, 3.5, 'as', 6), (None, None, 6.888893, 'bb', 9),
                  ('a', 66, 77, 'sdfasdf', 45)]
        nrows = len(values)
    
        arr = ma.zeros(nrows, dtype=[('c1', 'S1'),('c2', np.int), ('c3', np.float), 
                                     ('c4', 'S8'), ('c5', np.int)])
    
        for i, row in enumerate(values):
            for j, cell in enumerate(values[i]):
                if values[i][j] is None:
                    arr.mask[i][j] = True
                else:
                    arr.data[i][j] = cell
    
        print arr
    

    【讨论】:

      【解决方案2】:

      NaN 没有整数表示。您可以切换到浮点,或者在填充数组时构造掩码:

      >>> values = [1, 2, None, 4]
      >>> arr = np.empty(len(values), dtype=np.int64)
      >>> mask = np.zeros(len(values), dtype=np.bool)
      >>> for i, v in enumerate(values):
      ...     if v is None:
      ...         mask[i] = True
      ...     else:
      ...         arr[i] = v
      ...         
      >>> np.ma.array(arr, mask=mask)
      masked_array(data = [1 2 -- 4],
                   mask = [False False  True False],
             fill_value = 999999)
      

      【讨论】:

      • 但是问题来自于使用元组。如果你定义一个元组列表,它会抛出异常:例如values = [(1, 2), (None, 4)] arr = np.empty(len(values), dtype=[('c1', np.int64),('c2', np.int64)])
      • @tetrarquis:然后使用np.empty((len(values), len(values[0]))。我发布的只是一个示例,您必须根据您的用例对其进行调整。
      猜你喜欢
      • 2022-09-23
      • 2021-08-15
      • 2017-12-30
      • 1970-01-01
      • 1970-01-01
      • 2017-06-11
      • 2018-01-15
      • 2017-03-17
      • 1970-01-01
      相关资源
      最近更新 更多