Home > database >  Remove all individual row values that are not in Table2 from Table1, while keeping the count of Tabl
Remove all individual row values that are not in Table2 from Table1, while keeping the count of Tabl

Time:04-30

I have two tables:
Table1

Values     | Count  
a, b, e, f | 20 
a, f, j    | 30
b          | 40
c          | 50

Table2

Values     | Count  
a          | 5 
b          | 10
c          | 10
d          | 20

The problem is that I want to remove all individual values that are not in Table2 from Table1, while keeping the count of Table1. For example, because the values, e, f, j are not in Table2, I want to remove only those values from Table1 without changing the count. So the final Table1 needs to look like this.

Table1

Values     | Count  
a, b       | 20 
a,         | 30
b          | 40
c          | 50

This what I've tried so far:
I've converted the both, the Values and Count columns to lists. Split the lists. And then Flattened the lists.

Table1["Values"].tolist()

newList = []
for item in values2:
    newList.append(item.split(","))
    newList

output = [] 
def removeNestings(newList):
    for i in newList:
        if type(i) == list:
            removeNestings(i)
        else:
            output.append(i)

But in the process, I lose the count. That's where I'm stuck. I cannot keep the count. Can someone please help me out?

CodePudding user response:

Try this,

t1 = [["a, b, e, f",20],["a, f, j",30],["b",40],["c",50]]
t2 = [["a",5],["b",10],["c",10],["d",20]]

idx = [i[0] for i in t2]              #["a", "b", "c", "d"]
for item in t1:
    new_value = item[0].split(", ")   #["a", "b", "e", "f"]
    for v in item[0].split(", "):
        if v not in idx:
            new_value.remove(v)       #["a", "b"]
    item[0] = ", ".join(new_value)    #"a, b"
print(*t1, sep="\n")

Result:

[["a, b", 20], ["a", 30], ["b", 40], ["c", 50]]
  • Related