NumPy如何使用genfromtxt導(dǎo)入數(shù)據(jù)

本篇內(nèi)容主要講解“NumPy如何使用genfromtxt導(dǎo)入數(shù)據(jù)”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“NumPy如何使用genfromtxt導(dǎo)入數(shù)據(jù)”吧!

讓客戶滿意是我們工作的目標(biāo),不斷超越客戶的期望值來自于我們對這個行業(yè)的熱愛。我們立志把好的技術(shù)通過有效、簡單的方式提供給客戶,將通過不懈努力成為客戶在信息化領(lǐng)域值得信任、有價(jià)值的長期合作伙伴,公司提供的服務(wù)項(xiàng)目有:域名注冊、網(wǎng)站空間、營銷軟件、網(wǎng)站建設(shè)、康保網(wǎng)站維護(hù)、網(wǎng)站推廣。

簡介

在做科學(xué)計(jì)算的時(shí)候,我們需要從外部加載數(shù)據(jù),今天給大家介紹一下NumPy中非常有用的一個方法genfromtxt。genfromtxt可以分解成兩步,第一步是從文件讀取數(shù)據(jù),并轉(zhuǎn)化成為字符串。第二步就是將字符串轉(zhuǎn)化成為指定的數(shù)據(jù)類型。

genfromtxt介紹

先看下genfromtxt的定義:

numpy.genfromtxt(fname, dtype=<class 'float'>, comments='#', delimiter=None, skip_header=0, skip_footer=0, converters=None, missing_values=None, filling_values=None, usecols=None, names=None, excludelist=None, deletechars=" !#$%&'()*+, -./:;<=>?@[\]^{|}~", replace_space='_', autostrip=False, case_sensitive=True, defaultfmt='f%i', unpack=None, usemask=False, loose=True, invalid_raise=True, max_rows=None, encoding='bytes')

genfromtxt可以接受多個參數(shù),這么多參數(shù)中只有fname是必須的參數(shù),其他的都是可選的。

fname可以有多種形式,可以是file, str, pathlib.Path, list of str, 或者generator。

如果是單獨(dú)的str,那么默認(rèn)是本地或者遠(yuǎn)程文件的名字。如果是list of str,那么每個str都被當(dāng)做文件中的一行數(shù)據(jù)。如果傳入的是遠(yuǎn)程的文件,這個文件會被自動下載到本地目錄中。

genfromtxt還可以自動識別文件是否是壓縮類型,目前支持兩種壓縮類型:gzip 和 bz2。

接下來我們看下genfromtxt的常見應(yīng)用:

使用之前,通常需要導(dǎo)入兩個庫:

from io import StringIOimport numpy as np

StringIO會生成一個String對象,可以作為genfromtxt的輸入。

我們先定義一個包含不同類型的StringIO:

s = StringIO(u"1,1.3,abcde")

這個StringIO包含一個int,一個float和一個str。并且分割符是 ,。

我們看下genfromtxt最簡單的使用:

In [65]: data = np.genfromtxt(s)In [66]: data
Out[66]: array(nan)

因?yàn)槟J(rèn)的分隔符是delimiter=None,所以StringIO中的數(shù)據(jù)會被作為一個整體轉(zhuǎn)換成數(shù)組,結(jié)果就是nan。

下面我們添加一個逗號分割符:

In [67]: _ = s.seek(0)In [68]: data = np.genfromtxt(s,delimiter=",")In [69]: data
Out[69]: array([1. , 1.3, nan])

這次有輸出了,但是最后一個字符串因?yàn)椴荒鼙晦D(zhuǎn)換成為float,所以得到了nan。

注意,我們第一行需要重置StringIO的指針到文件的開頭。這里我們使用 s.seek(0)。

那么怎么把最后一個str也進(jìn)行轉(zhuǎn)換呢?我們需要手動指定dtype:

In [74]: _ = s.seek(0)In [75]: data = np.genfromtxt(s,dtype=float,delimiter=",")In [76]: data
Out[76]: array([1. , 1.3, nan])

上面我們指定了所有的數(shù)組類型都是float,我們還可以分別為數(shù)組的每個元素指定類型:

In [77]: _ = s.seek(0)In [78]: data = np.genfromtxt(s,dtype=[int,float,'S5'],delimiter=",")In [79]: data
Out[79]: array((1, 1.3, b'abcde'), dtype=[('f0', '<i8'), ('f1', '<f8'), ('f2', '<U')])

我們分別使用int,float和str來對文件中的類型進(jìn)行轉(zhuǎn)換,可以看到得到了正確的結(jié)果。

除了指定類型,我們還可以指定名字,上面的例子中,我們沒有指定名字,所以使用的是默認(rèn)的f0,f1,f2??匆粋€指定名字的例子:

In [214]: data = np.genfromtxt(s, dtype="i8,f8,S5",names=['myint','myfloat','mystring'], delimiter=",")In [215]: data
Out[215]:array((1, 1.3, b'abcde'),  dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', 'S5')])

分隔符除了使用字符之外,還可以使用index:

~~~pythonIn [216]: s = StringIO(u”11.3abcde”)
In [216]: s = StringIO(u"11.3abcde")
In [217]: data = np.genfromtxt(s, dtype=None, names=['intvar','fltvar','strvar'],
…: delimiter=[1,3,5])

In [218]: data
Out[218]:
array((1, 1.3, b'abcde'),
dtype=[('intvar', '<i8'), ('fltvar', '<f8'), ('strvar', 'S5')])

<pre><code class="">上面我們使用index作為s的分割。

# 多維數(shù)組

如果數(shù)據(jù)中有換行符,那么可以使用genfromtxt來生成多維數(shù)組:

~~~Python
>>> data = u”1, 2, 3\n4, 5, 6″
>>> np.genfromtxt(StringIO(data), delimiter=”,”)
array([[ 1., 2., 3.],
[ 4., 5., 6.]])

autostrip

使用autostrip 可以刪除數(shù)據(jù)兩邊的空格:

>>> data = u"1, abc , 2\n 3, xxx, 4">>> # Without autostrip>>> np.genfromtxt(StringIO(data), delimiter=",", dtype="|U5")array([['1', ' abc ', ' 2'],   ['3', ' xxx', ' 4']], dtype='<U5')>>> # With autostrip>>> np.genfromtxt(StringIO(data), delimiter=",", dtype="|U5", autostrip=True)array([['1', 'abc', '2'],   ['3', 'xxx', '4']], dtype='<U5')

comments

默認(rèn)的comments 是 # ,數(shù)據(jù)中所有以# 開頭的都被看做是注釋。

>>> data = u"""#
... # Skip me !
... # Skip me too !
... 1, 2
... 3, 4
... 5, 6 #This is the third line of the data
... 7, 8
... # And here comes the last line
... 9, 0
... """
>>> np.genfromtxt(StringIO(data), comments="#", delimiter=",")
array([[1., 2.],
       [3., 4.],
       [5., 6.],
       [7., 8.],
       [9., 0.]])

跳過行和選擇列

可以使用skip_header 和 skip_footer 來跳過返回的數(shù)組特定的行:

>>> data = u"\n".join(str(i) for i in range(10))
>>> np.genfromtxt(StringIO(data),)
array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.])
>>> np.genfromtxt(StringIO(data),
...               skip_header=3, skip_footer=5)
array([ 3.,  4.])

可以使用usecols 來選擇特定的行數(shù):

>>> data = u"1 2 3\n4 5 6"
>>> np.genfromtxt(StringIO(data), usecols=(0, -1))
array([[ 1.,  3.],
       [ 4.,  6.]])

如果列還有名字的話,可以用usecols 來選擇列的名字:

>>> data = u"1 2 3\n4 5 6"
>>> np.genfromtxt(StringIO(data),
...               names="a, b, c", usecols=("a", "c"))
array([(1.0, 3.0), (4.0, 6.0)],
      dtype=[('a', '<f8'), ('c', '<f8')])
>>> np.genfromtxt(StringIO(data),
...               names="a, b, c", usecols=("a, c"))
    array([(1.0, 3.0), (4.0, 6.0)],
          dtype=[('a', '<f8'), ('c', '<f8')])

到此,相信大家對“NumPy如何使用genfromtxt導(dǎo)入數(shù)據(jù)”有了更深的了解,不妨來實(shí)際操作一番吧!這里是創(chuàng)新互聯(lián)網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

文章名稱:NumPy如何使用genfromtxt導(dǎo)入數(shù)據(jù)
分享網(wǎng)址:http://muchs.cn/article14/pdgpge.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供搜索引擎優(yōu)化小程序開發(fā)、Google、移動網(wǎng)站建設(shè)、App開發(fā)、營銷型網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站托管運(yùn)營