Solve the problem of np. load coding in python3

  • 2021-10-15 11:02:16
  • OfStack

Since the default encoding in Python2 is ASCII, the default encoding in Python3 is UTF-8.

Question:

Therefore, when using np. load (det. npy), an error will appear:

you may need to pass the encoding= option to numpy.load

Solution:

When this happens, just use np. load (det. npy, encoding = "latin1").

Addition: python resolves numpy import garbled problem----solved

When using loadtxt of numpy, an error is found.

The experience is as follows:


// Visual Studio Code
var foo = 'bar';
import numpy as np 
if __name__ == "__main__":
 dataset = np.loadtxt("C:/Users/yanruyu/Documents/code/python/GA/dataset.txt") 
 print(dataset)

Printed results:

ValueError: could not convert string to float: '1, 1'

Solving experience:

1st time:


// Visual Studio Code
var foo = 'bar';
import numpy as np 
if __name__ == "__main__":
 dataset = np.loadtxt("C:/Users/yanruyu/Documents/code/python/GA/dataset.txt",dtype="str") # Default to float, Need dtype
 print(dataset)

Printed results:

['1, 1', '1, 2', '1.5, 1.5', '3, 4', '4, 4']

Second time:


// Visual Studio Code
var foo = 'bar';
import numpy as np 
if __name__ == "__main__":
 dataset = np.loadtxt("C:/Users/yanruyu/Documents/code/python/GA/dataset.txt",dtype="str",encoding='utf-8') # Default to float, Need dtype
 print(dataset)

Printed results:

['1, 1, A', '1, 2, A', '1.5, 1.5, A', '3, 4, B', '4, 4, B']

After optimization


// Visual Studio Code
var foo = 'bar';
import numpy as np 
if __name__ == "__main__":
 dataset = np.loadtxt("C:/Users/yanruyu/Documents/code/python/GA/dataset.txt",dtype="str",encoding='utf-8',delimiter=',') # Default to float, Need dtype
 # x=dataset[:,:-1] 
 print(dataset)

Printed results:

PS C:\Users\yanruyu > & D:/Anaconda3/python.exe c:/Users/yanruyu/Documents/code/python/GA/text.py

[['1' '1, A']

['1' '2, A']

['1.5' '1.5, A']

['3' '4, B']

['4' '4, B']]


Related articles: