在python列中将这些对象转换为int64

时间:2019-12-09 14:25:55

标签: python dataframe data-cleaning

另一个简单的问题。我必须清理一些数据,并且一些列需要采用int64格式,而不是它们现在所包含的对象(提供了示例)。我将如何统一重新格式化这些列。

print(data.Result)
0    98.8 PG/ML   H
1           8.20000
2    26.8 PG/ML   H
3    40.8 PG/ML   H
4            CREDIT
5          15.30000

1 个答案:

答案 0 :(得分:1)

您可以使用正则表达式进行解析:

import re

def parse_int(s):
    """
    A fast memoized function which builds a lookup dictionary then maps values to the series
    """
    map_dict = {x:float(re.findall('[0-9.]+',x)[0]) for x in s.unique() if re.search('[0-9.]+',x)}
    return s.map(map_dict)

data['Result'] = parse_int(data['Result'])

上面的函数从系列中获取所有唯一值,并将它们与其等效的float配对。在重复值的情况下,这是一种非常有效的方法。然后,该函数将这些值对(map_dict)映射到原始序列(s)。