【问题标题】:Grouping categories into smaller categories in a column在列中将类别分组为更小的类别
【发布时间】:2021-03-08 08:24:36
【问题描述】:

我想在 python 中对一列进行分组,使所有颜色都按颜色分组,汽车按汽车分组,所有其他值按其他分组。其他值的数量非常多,因此很难手动输入它们。但是,汽车和颜色的值可以手动替换。

例如,列如下所示

Column name
Red
Blue
Green
BMW
Toyata
djdjd
dhfh
sher
dhfg

其他值的数量非常多,因此手动输入它们很困难。但是,汽车和颜色的值可以手动替换。

结果应该是

Column name
Colour
Colour
Colour
Car
Car
Other 
Other
Other
Other

【问题讨论】:

    标签: python for-loop grouping categorical-data columnsorting


    【解决方案1】:

    我猜,当你提到列时,你的意思是 Pandas df 列。

    可以制作字典,如下

    replace_dict = {'Red' : 'Color',
                    'Blue': 'Color',
                     .....
                     .....
                    'Toyata': 'Car',
                     .....
                     }
    

    然后对列应用替换功能。

    喜欢

    df['Column name'].replace(replace_dict)
    

    【讨论】:

    • 是的,对于颜色和汽车,我可以使用字典并替换它们,但是有没有办法将所有不是汽车或颜色的值替换给其他人,而无需手动输入所有值
    • replace_dict = {k: None for k in df['Column name'].unique()} 将为您构建空字典,因此您无需在字典中键入值.你可以只输入你需要的,rest 将变为 Null I
    【解决方案2】:

    我不知道您的列是什么类型的对象,但是如果您将列转换为列表,则以下凌乱的脚本将起作用:

    ColoursList = ['Blue', 'Green', 'Yellow']
    CarsList = ['BMW','Mercedes','Opel']
    ValuesList = ['Blue', 'jfefe', 'bndf', 'Green', 'Mercedes', 'Yellow']
    GroupedList = []
    
    for ValueIndex in range(0,len(ValuesList)):
        GroupedValue = ''
        #Colour check
        for ColourIndex in range(0,len(ColoursList)):
            if ValuesList[ValueIndex] == ColoursList[ColourIndex]:
                GroupedValue = 'Colour'
        #Car check
        for CarIndex in range(0,len(ColoursList)):
            if ValuesList[ValueIndex] == CarsList[CarIndex]:
                GroupedValue = 'Car'
        print(GroupedValue)
        
        if GroupedValue == '':
            GroupedValue = 'Other'
        
        GroupedList.append(GroupedValue)
    
    print(ValuesList)
    print(GroupedList)
    

    【讨论】:

      猜你喜欢
      • 2017-10-04
      • 1970-01-01
      • 1970-01-01
      • 2021-07-15
      • 1970-01-01
      • 1970-01-01
      • 2022-09-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多