我有一个来自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化风格的解决方案。我使用的是一个非常大的数据库,所以复杂性很重要。
2条答案
按热度按时间jrcvhitl1#
pandas在这方面做得很好:
输出:
gkl3eglg2#
如果您的元组很小且大小固定,则可以使用列表理解:
或者稍微短一点: