I tried to save 2 dimensional array to a file and load it back. But not sure how to fix it. please advise. thanks.
import numpy as np
x = [['ABC', 123.45], ['DEF', 678.90]]
np.savetxt('text.txt',x)
y = np.loadtxt('text.txt')
Default format string (
fmt
parameter) for the
np.savetxt
method coincide to floating point numbers, so, you need to change
fmt
to '%s' (strings):
import numpy as np
x = [['ABC', 123.45], ['DEF', 678.90]]
np.savetxt('text.txt', x, fmt='%s')
# default dtype for np.loadtxt is also floating point, change it, to be able to load mixed data.
y = np.loadtxt('text.txt', dtype=np.object)
Is it a way to keep y same type (list) as x after loaded? Thanks.
You can convert
y
to list using
.tolist()
method, e.g.
y = np.loadtxt('text.txt', dtype=np.object)
y = y.tolist()
Another way is to use standard
pickle module.