therion
therion

Reputation: 445

Replace an element in a pandas dataframe column if present in another dataframe column

There are two dataframes given by:

train = pd.DataFrame({'Alpha': [10, 22, 10, 45, 44, 21, 62, 84, 32, 97, 38]})
test = pd.DataFrame({'Alpha': [10, 97, 32, 34, 44, 76, 49]})

If each value of test is not present in train, then the test values should be replaced with -1.

Expected output: [10, 97, 32, -1, 44, -1, -1] since 34, 76 and 49 are not present in train.

What I tried:

for x in test.Alpha:
    if x not in train.Alpha:
        test = test.Alpha.replace(x, -1)

Not working.

Upvotes: 0

Views: 45

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150735

You can do with isin:

test.loc[~test.Alpha.isin(train.Alpha), 'Alpha'] = -1

Output of test:

   Alpha
0     10
1     97
2     32
3     -1
4     44
5     -1
6     -1

Upvotes: 2

Related Questions