📜  Python中的 numpy.loadtxt()

📅  最后修改于: 2022-05-13 01:54:43.369000             🧑  作者: Mango

Python中的 numpy.loadtxt()

Python中的numpy.load()用于从文本文件中加载数据,旨在成为简单文本文件的快速阅读器。

请注意,文本文件中的每一行必须具有相同数量的值。

代码#1:

# Python program explaining 
# loadtxt() function
import numpy as geek
  
# StringIO behaves like a file object
from io import StringIO   
  
c = StringIO("0 1 2 \n3 4 5")
d = geek.loadtxt(c)
  
print(d)

输出 :

[[ 0.  1.  2.]
 [ 3.  4.  5.]]


代码#2:

# Python program explaining 
# loadtxt() function
import numpy as geek
  
# StringIO behaves like a file object
from io import StringIO   
  
c = StringIO("1, 2, 3\n4, 5, 6")
x, y, z = geek.loadtxt(c, delimiter =', ', usecols =(0, 1, 2), 
                                                unpack = True)
  
print("x is: ", x)
print("y is: ", y)
print("z is: ", z)

输出 :

x is:  [ 1.  4.]
y is:  [ 2.  5.]
z is:  [ 3.  6.]


代码#3:

# Python program explaining 
# loadtxt() function
import numpy as geek
  
# StringIO behaves like a file object
from io import StringIO   
  
d = StringIO("M 21 72\nF 35 58")
e = geek.loadtxt(d, dtype ={'names': ('gender', 'age', 'weight'),
                                  'formats': ('S1', 'i4', 'f4')})
  
print(e)

输出 :

[(b'M', 21,  72.) (b'F', 35,  58.)]