[英]How to convert float to int in a list in python?
我在将float转换为python列表中的int时遇到问题。
列表的元素之一如下所示:
{'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'
}
我无法将age
和year
转换为int。
我的代码:
for i in range(len(d)):
int(d[i]['age'])
我得到以下错误
ValueError: cannot convert float NaN to integer
所需的输出:
{'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'
}
您的年龄列表中包含NaNs
。 如果无法删除这些代码,则可以尝试将代码包装在try-except
语句中:
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
您可能需要计算NaN的数量,以便您知道缺少多少个条目。
使用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()})
输出 :
{
'artForm': 'Madur', 'artistName': 'Bharati Dolai', 'gender': 'F',
'district': 'Paschim Medinipur', 'phone': '',
'artisanCard': {'exists': 'N', 'cardNo': ''},
'dob': '', 'age': 45, 'year': 1971,
'education': 'I', 'childrenGoToSchool': 'Y'
}
编辑 :
如果只需要特定的列:
print({k: int(v) for k, v in d.items() if k == 'age' or k == 'year' and not math.isnan(v)})
输出 :
{'age': 45, 'year': 1971}
一支班轮
>>> 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}
您的某些值为NaN
。 另外,您错过了分配操作。
import math
for i in range(len(d)):
if not math.isnan(d[i]['age']):
d[i]['age'] = int(d[i]['age'])
在try
块中执行相同的操作,因为'age'
键的某些值为NaN
:
for i in range(len(d)):
try:
d[i]['age'] = int(d[i]['age'])
except Exception as e1:
pass
这也将有助于避免'age'
键具有空字符串(例如''
。
尝试这个:
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)
如果属性丢失或不正确,最好具有默认值。 并且您不需要使用range来循环列表。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.