重命名Python中的拼写错误的分类值

时间:2018-10-17 08:23:28

标签: python python-3.x pandas categorical-data

我有一个类别变量,其中某些值拼写错误或为“未知” /“未指定”。有没有一种方法可以使用最常见的名称(在我的情况下为“计算机”)重命名这些特定值?谢谢!

df['platform'].value_counts()
Out[41]: 
Computer       5433941
Tablet         4415217
Mobile         4229074
Unspecified    1716370
Unknown          48113
Big screen        9850
UNKNOWN            269
comp                 1
Name: platform, dtype: int64

2 个答案:

答案 0 :(得分:0)

您可以定义一个函数来替换标签,并在列上使用Apply。

to_replace = ['Unspecified','Unknown]
target = 'Computer'
def label_restrictor(label,to_replace=to_replace,target=target):
    if label in to_replace:
        return(target)
    else:
        return(label)

然后将此功能应用于您关注的列:

df.platform.apply((lambda label: label_restrictor(label)),inplace=True)

瞧瞧!

答案 1 :(得分:0)

replace = ['Unspecified', 'Unknown']
final_value = df['platform'].value_counts().idxmax()
def replace_values(x):
    if x in replace:
        return final_value
    else:
        return x
df['platform'] = df['platform'].apply(replace_values)

使用idxmax,可以获得频率最大的值。然后使用apply函数替换值

如果“平台”列中的值也为空:

df['platform'] = df['platform'].apply(lambda x: replace_values(x) if pd.notnull(x) else x)