I have a list of float numbers (appear as strings) and NaN values.
import numpy as np
mylist = ['1.0', '0.0', np.nan, 'a']
I need to convert float string values into integer string values, while ignoring the rest of records:
mylist = ['1', '0', np.nan, 'a']
How can I do it?
I wrote the following code, but I don't know how to handle the exceptions np.nan, a, etc.
mylist2 = []
for i in mylist:
mylist2.append(str(int(float(n))))
You can use a map that calls a function to convert them to ints:
def to_int(x):
try:
x = str(int(float(x)))
except:
pass
return x
np.array(list(map(to_int, mylist)), dtype=object)
# array(['1', '0', nan, 'a'], dtype=object)```
Although there are different ways to achieve this. but let's go your way.
This might help.
mylist2 = []
for i in mylist:
try:
mylist2.append(str(int(float(n))))
except:
pass
Assuming you want to just use the original values when they are not numeric strings that can be converted to integers, you can write a helper function to try doing the conversion, and return the original value if an exception is raised.
def try_int(s):
try:
return str(int(float(s)))
except:
return s
mylist2 = [try_int(s) for s in mylist]
Be aware that the conversion from a float string to an int can sometimes make the strings much longer; for example, the string '9e200' will be converted to an integer string with 201 digits.
Related
This question already has answers here:
Convert all strings in a list to int
(10 answers)
Closed last month.
have a list with numeric strings, like so:
numbers = ['1', '5', '10', '8'];
I would like to convert every list element to integer, so it would look like this:
numbers = [1, 5, 10, 8];
The natural Python way of doing this is using list comprehensions:
intlist = [int(element) for element in stringlist]
This syntax is peculiar to the Python language and is a way to perform a "map" with an optional filtering step for all elements of a sequnce.
An alterantive way, which will be more familiar for programmers that know other languages is to use the map built-in: in it, a function is passed as the first parameter, and the sequence to be processed as the second parameter. The object returned by map is an iterator, that will only perform the calculations on each item as it is requested. If you want an output list, you should build a list out of the object returned by map:
numbers = list(map(int, stringlist))
You can use a simple function called map:
numbers = ['1', '5', '10', '8']
numbers = list(map(int, numbers))
print(numbers)
This will map the function int to each element in the iterable. Note that the first argument the map is a function.
you can use generator objects
[int(i) for i in numbers]
Sometimes int() gives convertion error if the input it's not a valid variable. In that case must create a code that wraps all convertion error.
numbers = []
not_converted = []
for element in string_numbers:
try:
number = int(element)
if isinstance(number, int):
numbers.append(number)
else:
not_converted.append(element)
except:
not_converted.append(element)
If you expect that the input it's aways a string int you can simply convert like:
numbers = [int(element) for element in string_numbers]
You can use the below example:-
numbers = ['3', '5', '7', '9']
numbers = list(map(int, numbers))
print(numbers)
Suppose I have a list ['a', '1','student'] in Python
I am iterating through this list and want to check which item in the list is numeric.
I have tried all(item.isdigit()), type(item)==str. but shows error.
note: Numeric values in list are enclosed in quotes so they are identified as strings.
How to get past that?
I am expecting to identify which item in list is numeric and which are alphabetical values. The challenge is the numeric values are enclosed in quotes identifying them as strings
If you are after an array of bools, you can use:
lst = ['a', '1', 'student']
y = [x.isdigit() for x in lst]
>>> y
[False, True, False]
Where x.isdigit() returns true if the string x represents a digit. You can also use [x.isnumeric() for x in lst] if you are after any string that is numeric. Which includes decimals.
Try isdigit() instead:
l = ['a', '1', 'student']
for item in l:
if item.isdigit():
print(f'{item} is a digit')
elif item.isalpha():
print(f'{item} is a letter')
In the example you gave, extracting a list containing all the numbers is done by:
myList = ['a', '1','student']
onlyNumbers = [x for x in myList if x.isdigit()]
print(onlyNumbers)
An important distinction to make is the difference between a "number" type (int, float or Decimal) and a string that represents the number. If you had a list containing items of both string and integer types, then you could extract the items by altering the previous example like so:
myList = ['a', 1,'student']
onlyNumbers = [x for x in myList if isinstance(x,int)]
print(onlyNumbers)
Note how the 1 is no longer quoted. This means that it is a integer type.
Here are some recommendations:
all(iterable,condition)
returns a single value indicating whether ALL values in an iterable are true. It does not extract all values which are true, which is a misconception you appear to have.
Instead of type(x)==str, you can do isinstance(x,str) which is slightly cleaner.
To extract numbers from strings, you can use regular expressions. Alternatively, it is easier to attempt to convert the string to that number type:
anInteger = int("13")
aFloat = float("1")+float("1.2")
aComplex = complex("1+1j")
This is an example to show it working in full. It relies on python's numeric types throwing an exception when a bad representation of that type is passed to the type's constuctor.
def isNumberType(repStr : str, numType):
try:
numType(repStr)
return True
except:
return False
x = ["12.32","12","ewa"]
onlyIntegers = [int(val) for val in x if isNumberType(val,int)]
print(onlyIntegers)
I’m trying to find int values in an inputted list that contains floats and int values. The problem is the list read in looks like this:
List = [“14”,”8.00”,”2.00”,”3”]
How would I go about finding just the integer values in this list, not the floats? I’m presuming the type function won’t work since it’ll just say all the numbers are strings.
you can use ast module to identify the integer and float from strings.
In [16]: type(ast.literal_eval("3"))
Out[16]: int
In [17]: type(ast.literal_eval("3.0"))
Out[17]: float
Now using this concept with isinstance, you can filter out the integers:
In [7]: import ast
In [10]: a = ['14','8.00','2.00','3']
In [11]: a
Out[11]: ['14', '8.00', '2.00', '3']
In [12]: res = []
In [13]: for num in a:
...: if isinstance(ast.literal_eval(num),int):
...: res.append(num)
...:
In [14]: res
Out[14]: ['14', '3']
Try below code :
l = ["14","8.00","2.00","3"]
l = [int(i) for i in l if i.isdigit()]
print(l)
How do I append two digit integer into a list using for loop without splitting them. For example I give the computer 10,14,13,15 and I get something like 1,0,1,4,1,3,1,5. I tried to go around this, but I ended up with a new issue, which is Type Error: sequence item 0: expected string, int found
def GetNumbers(List):
q=[]
Numberlist = []
for i in List:
if i.isdigit():
q.append(int(i))
else:
Numberlist.append(''.join(q[:]))
del q[:]
return Numberlist
Ideal way will be to use str.split() function as:
>>> my_num_string = "10,14,13,15"
>>> my_num_string.split(',')
['10', '14', '13', '15']
But, since you mentioned you can not use split(), you may use regex expression to extract numbers from string as:
>>> import re
>>> re.findall('\d+', my_num_string)
['10', '14', '13', '15']
Else, if you do not want to go with any fancy method, you may achieve it with simple for loop as:
num_str, num_list = '', []
# ^ Needed for storing the state of number while iterating over
# the string character by character
for c in my_num_string:
if c.isdigit():
num_str += c
else:
num_list.append(num_str)
num_str = ''
The numbers in num_list will be in the form of str. In order to convert them to int, you may explicitly convert them as:
num_list = [int(i) for i in num_list] # OR, list(map(int, num_list))
code:
list=['1','85863','432','93','549834']
list.sort()
print (list)
Actual output:
>>>
['1', '432', '549834', '85863', '93']
#why sort is not working
Expected output:
['1','93','432','83863','549834']
I have tried other sort operations also but they are displaying same output.
when i tried to read list from keyboard input they are reading only strings but not int please help me why?
when i tried to read list from keyboard input they are reading only strings but not int please help me why
if x is a string, just use int(x) to convert to int
You're sorting strings (text), not by numerical values like integers
For your expected output you have to convert to ints first
my_list= ['1','85863','432','93','549834']
my_list = [int(x) for x in my_list]
Now you can sort numerically, and get a list of ints
my_list.sort()
N.B. avoid using list as variable name, it is a Python built-in
I presume you want to sort by the sum to match your expected output:
l = ['1','85863','432','93','549834']
l.sort(key=lambda x: sum(map(int,x)))
print(l)
['1', '432', '93', '83863', '549834']
You need to first convert the strings to int.
list = [int(ele) for ele in list]
list.sort()
print list
Without int:
lst = ['1','85863','432','93','549834']
lst.sort()
lst.sort(key=len)
print(lst)
This give:
['1', '93', '432', '85863', '549834']
And if you want integers…
my_int = int(input())
I simply missed the logic of converting a string into int.By default python input will be taken as a string. so,we can use any method mentioned in the answers to convert in to string and then sort() method works succesufully over int