Kallol
Kallol

Reputation: 2189

Replace list type column items by indices from other columns

I have a data frame like this,

df
col1     col2       col3             col4
 1       [1,2]    [0,0,0,0]      [0,0,0,0]
 0       [2,3]    [0,0,0,0]      [0,0,0,0]

Now I want to replace col3, col4 list items with 1 based on the index from col1 and col2. So the data frame should look like,

col1     col2       col3             col4
 1       [1,2]    [0,1,0,0]      [0,1,1,0]
 0       [2,3]    [1,0,0,0]      [0,0,1,1]    

I am trying to use apply function or custom functions but not getting desired results, looking for some pandas way to do this efficiently.

Upvotes: 1

Views: 29

Answers (1)

jezrael
jezrael

Reputation: 862711

Working with list in pandas is not possible very efficient, here is possible solution:

def f(x):
    x['col4'] = [1 if i in x['col2'] else 0 for i, y in enumerate(x['col4'])]
    x['col3'] = [1 if i ==  x['col1'] else 0 for i, y in enumerate(x['col3'])]
    return x

df = df.apply(f, axis=1)
print (df)
   col1    col2          col3          col4
0     1  [1, 2]  [0, 1, 0, 0]  [0, 1, 1, 0]
1     0  [2, 3]  [1, 0, 0, 0]  [0, 0, 1, 1]

Upvotes: 3

Related Questions