Remove element from list in pandas dataframe based on value in column

list.remove(x) removes the value in-place and returns None. That is why the above code is failing for you. You can also do something like the following.

a = [[1,2,3,4,5,6],[23,23,212,223,1,12]]
b = [1,1]
df = pd.DataFrame(zip(a,b), columns = ['a', 'b'])
for i, j in zip(df.a, df.b):
    i.remove(j)

print df

                        a  b
0         [2, 3, 4, 5, 6]  1
1  [23, 23, 212, 223, 12]  1

Here's an alternative way of doing it:

In []:
df2 = df.explode('a')
df['a'] = df2.a[df2.a != df2.b].groupby(level=0).apply(list)
df

Out[]:
                        a  b
0         [2, 3, 4, 5, 6]  1
1  [23, 23, 212, 223, 12]  1

Assuming row b only contains one value, then you can try with the following using a list comprehension within a function, and then simply apply it:

import pandas as pd
a = [[1,2,3,4,5,6],[23,23,212,223,1,12]]
b = [1,1]


df = pd.DataFrame(zip(a,b), columns = ['a', 'b'])
def removing(row):
    val = [x for x in row['a'] if x != row['b']]
    return val
df['c'] = df.apply(removing,axis=1)
print(df)

Output:

                           a  b                       c
0         [1, 2, 3, 4, 5, 6]  1         [2, 3, 4, 5, 6]
1  [23, 23, 212, 223, 1, 12]  1  [23, 23, 212, 223, 12]

Tags:

Python

Pandas