这是我的menu.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)]任何帮助我们都将不胜感激
发布于 2019-11-11 00:44:51
使用您的示例文件:
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‘是字节串数据类型,每个字符一个字节。这是Py2规范。'U12‘是unicode数据类型,每个字符4个字节。这是Py3规范。
这里的“元组”标记结构化数组的记录。
数组为1d,字段按名称访问:
In [352]: _.shape
Out[352]: (4,)
In [353]: __['Item']
Out[353]: array(['Curry Rice', 'Pork Chop', 'Seafood Soup', 'Salad'], dtype='<U12')发布于 2019-11-10 23:25:10
欢迎!
我认为你的问题看起来和How to use numpy.genfromtxt when first column is string and the remaining columns are numbers? 很相似。而且它看起来得到了广泛的回答。查看那里,并检查python doc中np.genfromtxt的dtype选项
发布于 2019-11-10 23:25:21
默认情况下,numpy.genfromtxt()假定每列的数据类型为浮点型。您可以向它传递关键字参数dtype=None,让它尝试猜测每一列的数据类型。
menu_items = np.genfromtxt("menu.csv", delimiter=',', names=True, dtype=None)https://stackoverflow.com/questions/58789967
复制相似问题