【问题标题】:How to merge rows that are each a list of strings.. excluding duplicates如何合并每个都是字符串列表的行..不包括重复项
【发布时间】:2023-03-24 02:41:01
【问题描述】:

我正在处理音乐数据,需要为回归算法 python 3 pandas 编码流派分类。如果分类为流派,我想将类别编码为 0 或 1。数据位于 pandas 数据框中并包含重复值。我想将所有行合并到一个唯一值列表中,然后使用 get_dummies 对每条记录进行编码..

第一次尝试:

for i in x:
    a = genres + list(i)
    genres.append(a)

第二次尝试:

x = list of genres (like below)
[j for i in x for j in i]

list(itertools.chain(x))

输入:

第 1 行 = ['hip hop', 'rock','pop rock','country']

第 2 行 = ['pop', 'rock', 'pop rock' ,'alternative rock']

预期输出:

new list = ['hip hop', 'rock','country','pop','pop rock','alternative rock']

最终输出

      | hip hop | rock | country | pop | pop rock | alternative rock |
row 1 |   1     | 1    |  1      | 0   | 1        |  0               |
row 2 |   0     | 1    |  0      | 1   | 1        |  1               |

【问题讨论】:

    标签: python list join merge encode


    【解决方案1】:

    如果元素的顺序不重要,您可以将每个列表视为set,找到union,然后转换回列表:

    def merge(r1, r2):
        return list(set().union(r1, r2))
    
    
    row_1 = ['hip hop', 'rock','pop rock','country']
    row_2 = ['pop', 'rock', 'pop rock' ,'alternative rock']
    
    print(merge(row_1, row_2))
    

    输出

    ['pop rock', 'alternative rock', 'country', 'hip hop', 'rock', 'pop']
    

    但是,如果(出现的)顺序确实很重要,您可以执行以下操作:

    from itertools import chain
    
    def merge_with_order(r1, r2):
    
        seen = set()
        result = []
        for e in chain(r1, r2):
            if e not in seen:
                seen.add(e)
                result.append(e)
    
        return result
    
    
    row_1 = ['hip hop', 'rock','pop rock','country']
    row_2 = ['pop', 'rock', 'pop rock' ,'alternative rock']
    
    print(merge_with_order(row_1, row_2))
    

    输出

    ['hip hop', 'rock', 'pop rock', 'country', 'pop', 'alternative rock']
    

    如果您更喜欢单线,请考虑使用collections.OrderedDict

    from itertools import chain
    from collections import OrderedDict
    
    
    def merge_with_order(r1, r2):
        return list(OrderedDict.fromkeys(chain(r1, r2)))
    

    【讨论】:

    • 感谢您的回复。这有帮助。我需要为数据框中的行或行列表执行此操作。
    猜你喜欢
    • 2017-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多