具有混合数据类型的列表的Numpy dtype [英] Numpy dtype for list with mixed data types

查看:54
本文介绍了具有混合数据类型的列表的Numpy dtype的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表,my_list,其中包含要转换为numpy数组的混合数据类型.但是,出现错误TypeError: expected a readable buffer object.请参阅下面的代码.我试图将代码基于 NumPy文档.

my_list = [['User_0', '2012-2', 1, 6, 0, 1.0], ['User_0', '2012-2', 5, 6, 0, 1.0], ['User_0', '2012-3', 0, 0, 4, 1.0]]
my_np_array = np.array(my_list, dtype='S30, S8, i4, i4, f32')   

解决方案

为什么不使用dtype=object?

 In [1]: my_list = [['User_0', '2012-2', 1, 6, 0, 1.0], ['User_0', '2012-2', 5,
6, 0, 1.0], ['User_0', '2012-3', 0, 0, 4, 1.0]]
In [2]: my_np_array = np.array(my_list, dtype=object)
In [3]: my_np_array
Out[3]:
array([['User_0', '2012-2', 1, 6, 0, 1.0],
       ['User_0', '2012-2', 5, 6, 0, 1.0],
       ['User_0', '2012-3', 0, 0, 4, 1.0]], dtype=object)
 

注意 这与内存使用情况有关,当您指定每列的dtype时,分配给ndarray的内存将小于当您使用dtype=object包含的python中所有可能类型的内存时,因此分配给每列的内存将最大. /p>

I have a list, my_list, with mixed data types that I want to convert into a numpy array. However, I get the error TypeError: expected a readable buffer object. See code below. I've tried to base my code on the NumPy documentation.

my_list = [['User_0', '2012-2', 1, 6, 0, 1.0], ['User_0', '2012-2', 5, 6, 0, 1.0], ['User_0', '2012-3', 0, 0, 4, 1.0]]
my_np_array = np.array(my_list, dtype='S30, S8, i4, i4, f32')   

解决方案

Why don't use dtype=object?

In [1]: my_list = [['User_0', '2012-2', 1, 6, 0, 1.0], ['User_0', '2012-2', 5,
6, 0, 1.0], ['User_0', '2012-3', 0, 0, 4, 1.0]]
In [2]: my_np_array = np.array(my_list, dtype=object)
In [3]: my_np_array
Out[3]:
array([['User_0', '2012-2', 1, 6, 0, 1.0],
       ['User_0', '2012-2', 5, 6, 0, 1.0],
       ['User_0', '2012-3', 0, 0, 4, 1.0]], dtype=object)

Note It's about memory usage, when you specify the dtype of each column, memory allocated to your ndarray will be less than when you use dtype=object which contain all possible type in python so the memory allocated for each column will be maximal.

这篇关于具有混合数据类型的列表的Numpy dtype的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆