日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

numpy genfromtxt 读取字符_numpy组队学习1: 输入输出

發(fā)布時間:2025/3/15 编程问答 15 豆豆
生活随笔 收集整理的這篇文章主要介紹了 numpy genfromtxt 读取字符_numpy组队学习1: 输入输出 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

內(nèi)容來源:

組隊學(xué)習(xí)?datawhale.club


import numpy as np

  • npy格式:以二進(jìn)制的方式存儲文件,在二進(jìn)制文件第一行以文本形式保存了數(shù)據(jù)的元信息(ndim,dtype,shape等),可以用二進(jìn)制工具查看內(nèi)容。
  • npz格式:以壓縮打包的方式存儲文件,可以用壓縮軟件解壓

np的讀取和保存

  • 讀取: numpy.save(file, arr, allow_pickle=True, fix_imports=True) Save an array to a binary file in NumPy .npy format.
  • 保存: numpy.load(file, mmap_mode=None, allow_pickle=False, fix_imports=True, encoding='ASCII') Load arrays or pickled objects from .npy, .npz or pickled files.
outfile = r'test.npy' np.random.seed(88) x = np.random.uniform(0,1,[3,5])# 均勻分布 np.save(outfile,x) y = np.load(outfile) yarray([[0.64755105, 0.50714969, 0.52834138, 0.8962852 , 0.69999119],[0.7142971 , 0.71733838, 0.22281946, 0.17515452, 0.45684149],[0.92873843, 0.00988589, 0.08992219, 0.85020027, 0.48562106]])

保存一系列數(shù)組

  • 函數(shù): numpy.savez(file, *args, **kwds) Save several arrays into a single file in uncompressed .npz format.,第一個參數(shù)是輸出的文件名,隨后參數(shù)都是需要保存的數(shù)組,不寫關(guān)鍵字參數(shù)的話,數(shù)組默認(rèn)是arr_0開始命名
  • 輸出的是一個壓縮文件,擴展名為npz,但是npz壓縮文件中的每一個文件都是save()類型保存的npy文件,文件的名字就是數(shù)組名字
  • load()自動識別npz文件,并且返回一個類似于字典的對象,可以通過數(shù)組名作為關(guān)鍵字獲取數(shù)組的內(nèi)容。
outfile = r'.test.npz' x = np.linspace(0, np.pi, 5) y = np.sin(x) z = np.cos(x) np.savez(outfile, x, y, z_d=z) data = np.load(outfile) np.set_printoptions(suppress=True) data.files['z_d', 'arr_0', 'arr_1'] print(data['arr_0']) # [0. 0.78539816 1.57079633 2.35619449 3.14159265]print(data['arr_1']) # [0. 0.70710678 1. 0.70710678 0. ]print(data['z_d']) # [ 1. 0.70710678 0. -0.70710678 -1. ][0. 0.78539816 1.57079633 2.35619449 3.14159265] [0. 0.70710678 1. 0.70710678 0. ] [ 1. 0.70710678 0. -0.70710678 -1. ]

文本文件處理

  • savetxt(),loadtxt()和genfromtxt()函數(shù)用來存儲和讀取文本文件(如TXT,CSV等)。genfromtxt()比loadtxt()更加強大,可對缺失數(shù)據(jù)進(jìn)行處理。
  • numpy.savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='n', header='', footer='', comments='# ', encoding=None) Save an array to a text file.
  • fname:文件路徑
  • X:存入文件的數(shù)組。
  • fmt:寫入文件中每個元素的字符串格式,默認(rèn)’%.18e’(保留18位小數(shù)的浮點數(shù)形式)。
  • delimiter:分割字符串,默認(rèn)以空格分隔。
    • numpy.loadtxt(fname, dtype=float, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0, encoding='bytes', max_rows=None) Load data from a text file.
  • fname:文件路徑。
  • dtype:數(shù)據(jù)類型,默認(rèn)為float。
  • comments: 字符串或字符串組成的列表,默認(rèn)為# , 表示注釋字符集開始的標(biāo)志。
  • skiprows:跳過多少行,一般跳過第一行表頭。
  • usecols:元組(元組內(nèi)數(shù)據(jù)為列的數(shù)值索引), 用來指定要讀取數(shù)據(jù)的列(第一列為0)。
  • unpack:當(dāng)加載多列數(shù)據(jù)時是否需要將數(shù)據(jù)列進(jìn)行解耦賦值給不同的變量。
    • numpy.genfromtxt(fname, dtype=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=''.join(sorted(NameValidator.defaultdeletechars)), replace_space='_', autostrip=False, case_sensitive=True, defaultfmt="f%i", unpack=None, usemask=False, loose=True, invalid_raise=True, max_rows=None, encoding='bytes') Load data from a text file, with missing values handled as specified.names:設(shè)置為True時,程序?qū)训谝恍凶鳛榱忻Q
    # txt文件 outfile = r'test.txt' x = np.arange(0, 10).reshape(2, -1) np.savetxt(outfile, x,fmt='%.4f') y = np.loadtxt(outfile) print(y)[[0. 1. 2. 3. 4.][5. 6. 7. 8. 9.]] # csv文件 outfile = r'test.csv' x = np.arange(0, 10, 0.5).reshape(4, -1) np.savetxt(outfile, x, fmt='%.3f', delimiter=',') y = np.loadtxt(outfile, delimiter=',') print(y)[[0. 0.5 1. 1.5 2. ][2.5 3. 3.5 4. 4.5][5. 5.5 6. 6.5 7. ][7.5 8. 8.5 9. 9.5]] # 導(dǎo)入 outfile = r'data.csv' x = np.loadtxt(outfile, delimiter=',', skiprows=1) print(x) x = np.loadtxt(outfile, delimiter=',', skiprows=1, usecols=(1, 2)) print(x) val1, val2 = np.loadtxt(outfile, delimiter=',', skiprows=1, usecols=(1, 2), unpack=True)#輸出按列元組話分配 print(val1) # [123. 110. 164.] print(val2) # [1.4 0.5 2.1][[ 1. 123. 1.4 23. ][ 2. 110. 0.5 18. ][ 3. 164. 2.1 19. ]] import numpy as npoutfile = r'.data.csv' x = np.genfromtxt(outfile, delimiter=',', names=True) print(x) # [(1., 123., 1.4, 23.) (2., 110., 0.5, 18.) (3., 164., 2.1, 19.)]print(type(x)) # <class 'numpy.ndarray'>print(x.dtype) # [('id', '<f8'), ('value1', '<f8'), ('value2', '<f8'), ('value3', '<f8')]print(x['id']) # [1. 2. 3.] print(x['value1']) # [123. 110. 164.] print(x['value2']) # [1.4 0.5 2.1] print(x['value3']) # [23. 18. 19.][[123. 1.4][110. 0.5][164. 2.1]] [123. 110. 164.] [1.4 0.5 2.1]

    文本輸出格式選擇

    np.set_printoptions(precision=None, threshold=None, edgeitems=None, linewidth=None, suppress=None, nanstr=None, infstr=None, formatter=None, sign=None, floatmode=None, --kwarg) #設(shè)置打印選項 recision:int or None浮點輸出的精度位數(shù)(默認(rèn)8)# 如floatmode不是fixed,可能是None

    threshold:int觸發(fā)匯總的數(shù)組元素總數(shù)而不是完整的repr(默認(rèn)1000) edgeitems:int在開頭和結(jié)尾的摘要中的數(shù)組項數(shù) 每個維度(默認(rèn)為3) linewidth:int每行用于插入的字符數(shù)# 換行符(默認(rèn)為75) suppress : bool,科學(xué)記數(shù)法啟用 # True用固定點打印浮點數(shù)符號,當(dāng)前精度中的數(shù)字等于零將打印為零。 # False用科學(xué)記數(shù)法;最小數(shù)絕對值是<1e-4或比率最大絕對值> 1e3。默認(rèn)值False nanstr:str浮點非字母數(shù)字的字符串表示形式(默認(rèn)為nan) infstr:str浮點無窮大字符串表示形式(默認(rèn)inf) sign:string,' - ','+'或'',控制浮點類型符號的打印。 # '+'打印正值標(biāo)志。''打印空格。' - '省略正值符號,默認(rèn)

    formatter:可調(diào)用字典,格式化功能 # 格式化設(shè)置類型: - 'bool' - 'int' - 'timedelta':'numpy.timedelta64' - 'datetime':numpy.datetime64 - 'float' - 'longfloat':128位浮點數(shù) - 'complexfloat' - 'longcomplexfloat':由兩個128位浮點組成 - 'numpystr' : types numpy.string_ and numpy.unicode_ - 'object' : np.object_ arrays - 'str':所有其他字符串

    # 用于一次設(shè)置一組類型的其他鍵:- 'all':設(shè)置所有類型- 'int_kind':設(shè)置'int'- 'float_kind':設(shè)置'float'和'longfloat'- 'complex_kind':設(shè)置'complexfloat'和'longcomplexfloat'- 'str_kind':設(shè)置'str'和'numpystr'

    floatmode:str控制precision選項的解釋 #浮點類型值: -'fixed':始終打印精確的'precision精度'小數(shù)位 -'unique':打印最小小數(shù)位數(shù),precision選項被忽略。 -'maxprec':打印最多precision小數(shù)位數(shù) -'maxprec_equal':最多打印precision小數(shù)位數(shù)

    legacy:string或False # 如為字符串“1.13”,則啟用1.13傳統(tǒng)打印模式。 # 如設(shè)置“False”,禁用傳統(tǒng)模式。無法識別的字符串將被忽略

    • numpy.get_printoptions() Return the current print options.返回之前的所有參數(shù)
    # 輸出設(shè)置 np.set_printoptions(threshold=20) x = np.arange(50) print(x) # [ 0 1 2 ... 47 48 49]np.set_printoptions(threshold=np.iinfo(np.int).max) print(x) # [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 # 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 # 48 49]eps = np.finfo(float).eps x = np.arange(4.) x = x ** 2 - (x + eps) ** 2 print(x) # [-4.9304e-32 -4.4409e-16 0.0000e+00 0.0000e+00] np.set_printoptions(suppress=True) print(x) # [-0. -0. 0. 0.]x = np.linspace(0, 10, 10) print(x) # [ 0. 1.1111 2.2222 3.3333 4.4444 5.5556 6.6667 7.7778 8.8889 # 10. ] np.set_printoptions(precision=2, suppress=True, threshold=5) print(x) # [ 0. 1.11 2.22 ... 7.78 8.89 10. ][ 0 1 2 ... 47 48 49] [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 2324 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 4748 49] [-0. -0. 0. 0.] [-0. -0. 0. 0.] [ 0. 1.11 2.22 3.33 4.44 5.56 6.67 7.78 8.89 10. ] [ 0. 1.11 2.22 ... 7.78 8.89 10. ] import numpy as np x = np.get_printoptions() print(x){'edgeitems': 3, 'threshold': 5, 'floatmode': 'maxprec', 'precision': 2, 'suppress': True, 'linewidth': 75, 'nanstr': 'nan', 'infstr': 'inf', 'sign': '-', 'formatter': None, 'legacy': False}

    作業(yè)

    第一題: 只打印或顯示numpy數(shù)組rand_arr的小數(shù)點后3位。

    • rand_arr = np.random.random([5, 3])【知識點:輸入和輸出】如何在numpy數(shù)組中只打印小數(shù)點后三位?

    第二題: 將numpy數(shù)組a中打印的項數(shù)限制為最多6個元素。【知識點:輸入和輸出】

    第三題:打印完整的numpy數(shù)組a而不中斷。【知識點:輸入和輸出】

    rand_arr = np.random.random([5,3]) # 第一題: 設(shè)置浮點精度 np.set_printoptions(precision=3) print(rand_arr)# 第二題:設(shè)置輸出元素個數(shù) rand_arr = np.arange(10) np.set_printoptions(edgeitems=3)#edgeitems=nums,nums就是左右兩邊省略的數(shù) print(rand_arr)[0 1 2 ... 7 8 9] # 打印完整函數(shù)不中斷 rand_arr = np.arange(10) np.set_printoptions(threshold=float('inf')) print(rand_arr)[0 1 2 3 4 5 6 7 8 9]

    總結(jié)

    以上是生活随笔為你收集整理的numpy genfromtxt 读取字符_numpy组队学习1: 输入输出的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。