如何在没有pandas或numpy的情况下清理数据?

2024-06-26 00:13:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须使用python清理数据以便于分析,但是,在这种情况下我不能使用pandas 要求和期望如下:

actual = preprocess([
            ('Survived', 'Pclass', 'Name', 'Gender', 'Age', 'Fare'),
            ('no', '3', 'Braund Mr. Owen Harris', 'male', '22', '7.25'),
            ('Dead', '3', 'Braund Ms. Maria', 'Female', '21', ''),
            ('Yes', '1', 'Cumings Mrs. John Bradley (Florence Briggs Thayer)', 'F', '38', '71.28'),
            ('', '3', 'Vander Planke Miss. Augusta', 'female', '', ''),
            ('Dead', '4', 'Lennon Mr. Denis', 'male', '13', '15.5')])

expected = (
                ('Survived', 'Pclass', 'Name', 'Gender', 'Age', 'Fare'),
                [
                    (False, 3, 'Braund Mr. Owen Harris', 'male', 22.0, 7.25),
                    (False, 3, 'Braund Ms. Maria', 'female', 21.0, 25.0),
                    (True, 1, 'Cumings Mrs. John Bradley (Florence Briggs Thayer)', 'female', 38.0, 71.28),
                    ('', 3, 'Vander Planke Miss. Augusta', 'female', '', 25.0), 
                    (False, 4, 'Lennon Mr. Denis', 'male', 13.0, 15.5)]
                ]
           )

在这种情况下,你能给我一些建议吗


Tags: namefalseage情况gendermalefemalemr
1条回答
网友
1楼 · 发布于 2024-06-26 00:13:12

缺少一些信息(例如,如何处理缺少的值?或者是否应过滤掉不完整的条目?是否需要对结果进行排序?),但我仍将尝试回答:

要实现转换元组“列”的类型和/或内容的预期结果,需要将旧值映射和/或类型转换为新值


映射字符串

您可以使用不同的方法将不同的输入值映射到一系列输出值。我将在回答中使用两种方法:(1)使用if ... else语句,(2)使用python方法执行switch ... case语句

为了从'Survived'的不同可能条目中获得bool值,我使用了方法(2)。为此,您使用映射设置了一个字典,然后从中为每个候选项获取相应的条目(请参见Replacements for switch statement in Python?)。您可以将其与字符串lower()函数结合使用,这样就可以忽略大小写(How do I lowercase a string in Python?)。您还可以添加一个默认值,以防在dict中找不到键,在下面的示例中,我使用None

例如:

entry = 'NO'

switcher_survived = {
    'no': False,
    'dead': False,
    'yes': True
}

result = switcher_survived.get(entry.lower(), None)

同样的方法可用于根据不同的输入可能性设定性别


类型转换

对于数字,您可以简单地将其转换为所需的类型。但是,只有当字符串包含可以成功转换的数字时,这才有效。请注意,在您的示例中,您有一个带有空字符串的条目,当您尝试强制转换时,它将导致ValueError。因此,您需要检查这一点,并且可能再次希望将默认值设置为某个值。我使用nan = float('NaN'),因为这是一种在不使用额外包的情况下维护正确类型的好方法(请参见Assigning a variable NaN in python without numpy

例如:

nan = float('NaN') 

entry = '2.5'

result = (float(entry) if float(entry) != "" else nan)

我在这里使用一行if-then-else语句(参见Putting a simple if-then-else statement on one line),因为这对最后的完整示例是有益的


把它放在一起

actual = [
        ('Survived', 'Pclass', 'Name', 'Gender', 'Age', 'Fare'),
        ('no', '3', 'Braund Mr. Owen Harris', 'male', '22', '7.25'),
        ('Dead', '3', 'Braund Ms. Maria', 'Female', '21', ''),
        ('Yes', '1', 'Cumings Mrs. John Bradley (Florence Briggs Thayer)', 'F', '38', '71.28'),
        ('', '3', 'Vander Planke Miss. Augusta', 'female', '', ''),
        ('Dead', '4', 'Lennon Mr. Denis', 'male', '13', '15.5')]


nan = float('NaN')

switcher_survived = {
    'no': False,
    'dead': False,
    'yes': True
}

switcher_gender = {
    'male': 'male',
    'm': 'male',
    'female': 'female',
    'f': 'female'
}

def process(lst):
    result = []
    current = 1
    while current < len(lst):
        tuple = (switcher_survived.get(lst[current][0].lower(),''),
                 int(lst[current][1]),
                 lst[current][2],
                 switcher_gender.get(lst[current][3].lower(),''),
                 (float(lst[current][4]) if lst[current][4] != "" else ''),
                 (float(lst[current][5]) if lst[current][5] != "" else 25.0)
                )
        result.append(tuple)
        current += 1
    return [lst[0], result]

expected = process(actual)

print(expected)

一些评论:

  • 在最后一个示例中,我将“Fare”列的默认值更改为25.0,以符合您的预期结果

  • 出于同样的原因,我还将“幸存”、“性别”和“年龄”的默认值分别更改为空字符串'',而不是NoneNaN。请注意,这违反了您自己的要求,因为空字符串显然不是boolfloat类型。这可能会在以后处理数据时产生影响。特别是,列“Survived”中的空字符串可以静默计算为False

  • 要过滤掉不完整的数据,可以将默认值更改回NoneNaN,并且只向最终数据集添加完整的行。为此,您可以检查元组的字段是否为None(请参见What is the best way to check if a tuple has any empty/None values in Python?):

         if not any(map(lambda x: (x is None) or (x is nan), tuple)):
             result.append(tuple)
    
  • 如果要按任意列对列表进行排序,可以在返回结果之前使用lambda函数作为sortkey(请参见Syntax behind sorted(key=lambda: ...))。例如,按名称排序:

     result = sorted(result, key=lambda tuple: tuple[2])
    

相关问题 更多 >