python中的字符串文字被单引号或双引号引起来。使用变量名,后跟等号和字符串的方式为变量分配字符串。您可以使用三个引号将多行字符串分配给变量。
# array of strings to array of floats using astype import numpy as np # initialising array ini_array = np.array(["1.1", "1.5", "2.7", "8.9"]) # printing initial array print ("initial array", str(ini_array)) # conerting to array of floats # using np.astype res = ini_array.astype(np.float) # printing final result print ("final array", str(res)) # array of strings to array of floats using fromstring import numpy as np # initialising array ini_array = np.array(["1.1", "1.5", "2.7", "8.9"]) # printing initial array print ("initial array", str(ini_array)) # conerting to array of floats # using np.fromstring ini_array = ', '.join(ini_array) ini_array = np.fromstring(ini_array, dtype = np.float, sep =', ' ) # printing final result print ("final array", str(ini_array)) # converting array of strings to array of floats using asarray import numpy as np # initialising array ini_array = np.array(["1.1", "1.5", "2.7", "8.9"]) # printing initial array print ("initial array", str(ini_array)) # conerting to array of floats # using np.asarray final_array = b = np.asarray(ini_array, dtype = np.float64, order ='C') # printing final result print ("final array", str(final_array))
输出结果
('initial array', "['1.1' '1.5' '2.7' '8.9']") ('final array', '[ 1.1 1.5 2.7 8.9]') ('initial array', "['1.1' '1.5' '2.7' '8.9']") ('final array', '[ 1.1 1.5 2.7 8.9]') ('initial array', "['1.1' '1.5' '2.7' '8.9']") ('final array', '[ 1.1 1.5 2.7 8.9]')