I am facing problem in converting float to int in python list.
One of the elements of the list looks like this:
{'artForm': 'Madur',
'artistName': 'Bharati Dolai',
'gender': 'F',
'district': 'Paschim Medinipur',
'phone': '',
'artisanCard': {'exists': 'N', 'cardNo': ''},
'dob': '',
'age': 45.0,
'year': 1971.0,
'education': 'I',
'childrenGoToSchool': 'Y'
}
I am unable to convert the age
and year
to int.
My code:
for i in range(len(d)):
int(d[i]['age'])
And I get the following error
ValueError: cannot convert float NaN to integer
Desired output:
{'artForm': 'Madur',
'artistName': 'Bharati Dolai',
'gender': 'F',
'district': 'Paschim Medinipur',
'phone': '',
'artisanCard': {'exists': 'N', 'cardNo': ''},
'dob': '',
'age': 45, #converted to int
'year': 1971, #converted to int
'education': 'I',
'childrenGoToSchool': 'Y'
}
You have some ages which are NaNs
in your list. If these cannot be removed you could try wrapping your code in a try-except
statement:
num_of_nans = 0
for entry in d:
try:
entry['age'] = int(entry['age'])
except ValueError:
entry['age'] = 'Age not known'
num_of_nans += 1
You may want to count the number of NaNs so you have an idea of how many of your entries are missing.
Using dict comprehension
:
import math
print({k: int(v) if k == 'age' or k == 'year' and not math.isnan(v) else v for k,v in d.items()})
OUTPUT :
{
'artForm': 'Madur', 'artistName': 'Bharati Dolai', 'gender': 'F',
'district': 'Paschim Medinipur', 'phone': '',
'artisanCard': {'exists': 'N', 'cardNo': ''},
'dob': '', 'age': 45, 'year': 1971,
'education': 'I', 'childrenGoToSchool': 'Y'
}
EDIT :
If you only want the specific columns:
print({k: int(v) for k, v in d.items() if k == 'age' or k == 'year' and not math.isnan(v)})
OUTPUT :
{'age': 45, 'year': 1971}
one liner
>>> test_dict = {"value1": 111.2, "value2": "asd", "value3": 13.232}
>>> test_dict = {key: int(math.floor(value)) if isinstance(value, float) else value for key, value in test_dict.items()}
>>> test_dict
{'value1': 111, 'value2': 'asd', 'value3': 13}
Some of your values are NaN
. Also, you missed the assignment operation.
import math
for i in range(len(d)):
if not math.isnan(d[i]['age']):
d[i]['age'] = int(d[i]['age'])
Do the same within a try
block as some of the values for the 'age'
key is NaN
:
for i in range(len(d)):
try:
d[i]['age'] = int(d[i]['age'])
except Exception as e1:
pass
This will also help to avoid those cases where 'age'
key has vacant string like ''
.
try this:
d = {'artForm': 'Madur',
'artistName': 'Bharati Dolai',
'gender': 'F',
'district': 'Paschim Medinipur',
'phone': '',
'artisanCard': {'exists': 'N', 'cardNo': ''},
'dob': '',
'age': 45.0,
'year': 1971.0,
'education': 'I',
'childrenGoToSchool': 'Y'
}
for i in range(len(d)):
#convert age to int and replace age
d['age'] = int(d['age'])
#if you want to convert all the floats to ints:
for k in list(d):#list d to get all the key
#test is float?
if isinstance(d[k], float):
#yes? convert it to int
d[k] = int(d[k])
#else pass
else:
pass
print(d)
Better to have a default value if the property is missing or incorrect. and you don't need to use range to loop a list.
for u in d:
try:
u["age"] = int(u["age"])
except ValueError:
u["age"] = 0
try:
u["year"] = int(u["year"])
except ValueError:
u["year"] = 0
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.