- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python - Ways to convert array of strings to array of floats
String literals in python are surrounded by either single quotation marks, or double quotation marks. Assigning a string to a variable is done with the variable name followed by an equal sign and the string. You can assign a multiline string to a variable by using three quotes.
Example
# 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))
Output
('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]')
Advertisements