Do with list comprehension,
In [24]: l = [['1', ' 1', ' 3'], ['2', ' 3', ' 5'], ['3'], ['4', ' 5'], ['5', ' 1'], ['6', ' 6'], ['7']]
In [25]: result = [map[int,i] for i in l]
Result
In [26]: print result
[[1, 1, 3], [2, 3, 5], [3], [4, 5], [5, 1], [6, 6], [7]]
Sometimes in a competitive coding environment, we get input in some other datatypes and we need to convert them into other forms this problem is the same as that we have an input in the form of string and we need to convert it into floats. Let’s discuss a few ways to convert an array of strings to an array of floats.
Example:
initial array: ['1.1' '1.5' '2.7' '8.9'] final array: [ 1.1 1.5 2.7 8.9]
Convert array of strings to array of floats using astype
Pandas astype[] is one of the most important methods. It is used to change the datatype of a series. if a column could be imported as a string but to do operations we have to convert it into a float, astype[] is used to do such data type conversions.
Python3
import
numpy as np
ini_array
=
np.array[[
"1.1"
,
"1.5"
,
"2.7"
,
"8.9"
]]
print
[
"initial array"
,
str
[ini_array]]
res
=
ini_array.astype[np.
float
]
print
[
"final array"
,
str
[res]]
Output:
initial array ['1.1' '1.5' '2.7' '8.9'] final array [ 1.1 1.5 2.7 8.9]
Convert array of strings to array of floats using np.fromstring
The numpy.fromstring[] function creates a new one-dimensional array initialized from text data in a string.
Python3
import
numpy as np
ini_array
=
np.array[[
"1.1"
,
"1.5"
,
"2.7"
,
"8.9"
]]
print
[
"initial array"
,
str
[ini_array]]
ini_array
=
', '
.join[ini_array]
ini_array
=
np.fromstring[ini_array, dtype
=
np.
float
,
sep
=
', '
]
print
[
"final array"
,
str
[ini_array]]
Output:
initial array ['1.1' '1.5' '2.7' '8.9'] final array [ 1.1 1.5 2.7 8.9]
Convert array of strings to array of floats using np.asarray[] and type
The numpy.asarray[]function is used when we want to convert the input to an array. Input can be lists, lists of tuples, tuples, tuples of tuples, tuples of lists and arrays.
Python3
import
numpy as np
ini_array
=
np.array[[
"1.1"
,
"1.5"
,
"2.7"
,
"8.9"
]]
print
[
"initial array"
,
str
[ini_array]]
final_array
=
b
=
np.asarray[ini_array,
dtype
=
np.float64, order
=
'C'
]
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]
Convert array of strings to array of floats using np.asfarray
The numpy.asfarray[] function is used when we want to convert input to a float type array. Input includes scalar, lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays.
Python3
import
numpy as np
ini_array
=
np.array[[
"1.1"
,
"1.5"
,
"2.7"
,
"8.9"
]]
print
[
"initial array"
,
str
[ini_array]]
final_array
=
b
=
np.asfarray[ini_array,dtype
=
float
]
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]