【问题标题】:Replace Items in Nested list using other Reference Dataframe使用其他参考数据框替换嵌套列表中的项目
【发布时间】:2021-02-09 06:36:23
【问题描述】:

我有一个列表,如下所示:

l1 = [[[1,0]],[[1,2],[6,9]],[[0,4]],[[0,4]], [[0,4]], [0]]

我有一个辅助数据框 df,将某些数字映射到列表:

D1 = [0,1,2,3]
D2 = [[100,0],[1,300,2],[2],[1,1,1]]
df= pd.DataFrame({'ref': D1,
 'val': D2})

我想检查列表l1 中的元素与数据框df'ref' 列中的值,如果相等,则将元素替换为dfD2 列中的相应值,如所需结果:

l3 = [ [[1,300,2],[100,0]],[[[1,300,2],[2]],[6,9]],[[100,0],4],[[100,0]],4], [[100,0],4], [100,0]]

我尝试了以下方法,但在执行一个循环后出现错误:

for i in range(1, len(l1)):
    for ii in range(0,len(l1[i])):
        for iii in range (0,len(l1[i][ii])):
            for j in range(0,len(df)):
                if l1[i][ii][iii] == df.ref[j]:
                    l1.linktest[i][ii][iii] = df.val[j]

并面对错误:ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

【问题讨论】:

    标签: python list for-loop nested mapping


    【解决方案1】:

    递归很适合解决这个问题。我使用了一个嵌套的辅助函数,它允许我重复重用同一个 df 实例。

    import pandas as pd
    
    l1 = [[[1, 0]], [[1, 2], [6, 9]], [[0, 4]], [[0, 4]], [[0, 4]], [0]]
    
    D1 = [0, 1, 2, 3]
    D2 = [[100, 0], [1, 300, 2], [2], [1, 1, 1]]
    df = pd.DataFrame({"ref": D1, "val": D2})
    
    
    def replacenest(ls: list, df: pd.DataFrame):
        # Here I create an internal recursive function which uses replacenest's df parameter repeatedly
        def recurse(element):
            if type(element) == list:
                # Call this function again on each element of the list
                return [recurse(e) for e in element]
            else:
                # Find all indices of "element" in df.loc and get a list of their values
                fill = list(df.loc[df.ref == element].val)
    
                if len(fill) == 1:
                    # there is a SINGLE item in "ref" that matches the element from ls
                    return fill[0]
                elif len(fill > 1):
                    # there are MULTIPLE items in "ref" that match the element from ls
                    # I am filling it with all matches in a list, but you can decide
                    #   what you want to do in this case
                    return fill
                else:
                    # no items in "ref" match this element from ls
                    # I will respond by not changing the element in ls
                    return element
    
        return recurse(ls)
    
    
    print(replacenest(l1, df))
    

    【讨论】:

    • 你先生是个巫师,非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多