1
a= {'A' : [1, 2,3,4],
'B' : ['FOOTBALL','BASKETBALL','HANDBALL','VOLLEYBALL'],
'C' : [[5,10,15,40],[1,4],[20,10,40],[10,40]]
}

How can I remove the element 40 from C if B is different to FOOTBALL Like this :

    A   B   C
0   1   FOOTBALL    [5, 10, 15, 40]
1   2   BASKETBALL  [1, 4]
2   3   HANDBALL    [20, 10]
3   4   VOLLEYBALL  [10]

1 Answer 1

2

You can filter both sides in mask and for remove 40 in list use lambda function:

df = pd.DataFrame(a)

m = df['B'].ne('FOOTBALL')
df.loc[m, 'C'] = df.loc[m, 'C'].apply(lambda x: [y for y in x if y!=40])
print (df)
   A           B                C
0  1    FOOTBALL  [5, 10, 15, 40]
1  2  BASKETBALL           [1, 4]
2  3    HANDBALL         [20, 10]
3  4  VOLLEYBALL             [10]

Alternative:

m = df['B'].ne('FOOTBALL')
df.loc[m, 'C'] = [[y for y in x if y!=40] for x in df.loc[m, 'C']]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.