sqlite 使用操作从列表创建NumPy数组

jmo0nnb3  于 2022-11-15  发布在  SQLite
关注(0)|答案(2)|浏览(159)

我有一个来自SQLite数据库的Python列表中的数据,格式如下:

# This is an example
data = [(1, '12345', 1, 0, None), (1, '34567', 1, 1, None)]

从这个元组列表中,我想创建一个2D NumPy数组,将每个元组转换为一个数组。我还希望元组中索引1处的值从字符串转换为数字,如果没有,则最后一个索引处的值转换为0,否则为1。
之后它应该是什么样子:

transformed_data = np.asarray([[1, 12345, 1, 0, 0], [1, 34567, 1, 1, 0]])

我可以使用简单的for循环,但是我想要一个带有原生NumPy方法或其他方法的更具Python化风格的解决方案。我使用的是一个非常大的数据库,所以复杂性很重要。

jrcvhitl

jrcvhitl1#

pandas在这方面做得很好:

import pandas as pd
                      # set up DataFrame
transformed_data = (pd.DataFrame(data)
                      # convert to numeric
                      .apply(pd.to_numeric, errors='coerce')
                      # replace null with 0
                      # trying to cast as integer if possible
                      .fillna(0, downcast='infer')
                      # convert to numpy array
                      .to_numpy()
                   )

输出:

array([[    1, 12345,     1,     0,     0],
       [    1, 34567,     1,     1,     0]])
gkl3eglg

gkl3eglg2#

如果您的元组很小且大小固定,则可以使用列表理解:

result = [(a, int(b), c, d, 0 if e is None else e) for a, b, c, d, e in data]

或者稍微短一点:

result = [(d[0], int(d[1]), *d[2:4], d[4] if d[4] else 0) for d in data]

相关问题