简体   繁体   English

如何在python中的列表中将float转换为int?

[英]How to convert float to int in a list in python?

I am facing problem in converting float to int in python list. 我在将float转换为python列表中的int时遇到问题。

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. 我无法将ageyear转换为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. 您的年龄列表中包含NaNs If these cannot be removed you could try wrapping your code in a try-except statement: 如果无法删除这些代码,则可以尝试将代码包装在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

You may want to count the number of NaNs so you have an idea of how many of your entries are missing. 您可能需要计算NaN的数量,以便您知道缺少多少个条目。

Using dict comprehension : 使用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 . 您的某些值为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 : try块中执行相同的操作,因为'age'键的某些值为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 '' . 这也将有助于避免'age'键具有空字符串(例如''

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. 并且您不需要使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM