[英]Numpy: genfromtxt forming tuples
这是我的菜单。csv:
Item,Price
Curry Rice,3.5
Pork Chop,6
Seafood Soup,5
Salad,2.8
这是我的代码:
import numpy as np
menu_items = np.genfromtxt("menu.csv", delimiter=',',names=True)
print(menu_items)
我得到什么:
[(nan, 3.5) (nan, 6.2) (nan, 3. ) (nan, 2.8)]
当我使用 dtype=None 时:
[(b'Curry Rice', 3.5) (b'Pork Chop', 6.2) (b'Seafood Soup', 3. )
(b'Salad', 2.8)]
我想要的是:
[(Curry Rice, 3.5) (Pork Chop, 6.2) (Seafood Soup, 3. ) (Salad, 2.8)]
任何帮助表示赞赏
欢迎!
我认为您的问题看起来非常类似于How to use numpy.genfromtxt when first column is string and the remaining columns are numbers? . 它看起来得到了广泛的回答。 在那里查看并检查 python 文档中np.genfromtxt
的dtype
选项
默认情况下numpy.genfromtxt()
假定每列的数据类型是浮点数。 您可以通过将关键字参数dtype=None
传递给它,让它尝试猜测每列的数据类型。
menu_items = np.genfromtxt("menu.csv", delimiter=',', names=True, dtype=None)
使用您的示例文件:
In [349]: cat stack58789967.txt
Item,Price
Curry Rice,3.5
Pork Chop,6
Seafood Soup,5
Salad,2.8
In [350]: np.genfromtxt('stack58789967.txt',delimiter=',',names=True, dtype=None)
/usr/local/bin/ipython3:1: VisibleDeprecationWarning: Reading unicode
strings without specifying the encoding argument is deprecated. Set the
encoding, use None for the system default.
#!/usr/bin/python3
Out[350]:
array([(b'Curry Rice', 3.5), (b'Pork Chop', 6. ), (b'Seafood Soup', 5. ),
(b'Salad', 2.8)], dtype=[('Item', 'S12'), ('Price', '<f8')])
In [351]: np.genfromtxt('stack58789967.txt',delimiter=',',names=True, dtype=None, encoding=None)
Out[351]:
array([('Curry Rice', 3.5), ('Pork Chop', 6. ), ('Seafood Soup', 5. ),
('Salad', 2.8)], dtype=[('Item', '<U12'), ('Price', '<f8')])
'S12' 是 bytestring dtype,每个字符一个字节。 这是 Py2 规范。 'U12' 是 unicode dtype,每个字符 4 个字节。 这是 Py3 规范。
这里的“元组”标记了结构化数组的记录。
数组为 1d,字段按名称访问:
In [352]: _.shape
Out[352]: (4,)
In [353]: __['Item']
Out[353]: array(['Curry Rice', 'Pork Chop', 'Seafood Soup', 'Salad'], dtype='<U12')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.