簡體   English   中英

Numpy:genfromtxt 形成元組

[英]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.genfromtxtdtype選項

默認情況下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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM