bim1
bim1

Reputation: 97

Comparing 2 columns in a dataframe python

I'm trying to compare if a row in my dataframe as a certain value.

So for example: if word = 'bleu' and ink = 'blue', I want a new column in my dataframe 'congruent' = 1 and if not = 0.

I wrote this code :

import pandas as pd
import numpy as np
import random

word = ['bleu', 'rouge', 'vert', 'jaune']

ink = ['blue', 'red', 'green', 'yellow']

my_list_word = [random.choice(word) for _ in range(60)]

df = pd.DataFrame(my_list_word, columns=["word"])

my_list_ink = [random.choice(ink) for _ in range(60)]

df['ink'] = my_list_ink

df['congruent'] = 0

print(df)

I tried to do a loop but it didn't work, my congruent column kept all 0.

Someone knows how to do this ?

Thanks!

Upvotes: 1

Views: 114

Answers (2)

BENY
BENY

Reputation: 323376

By using merge

df1=pd.DataFrame({'word':word,'ink':ink})
df.merge(df1.assign(congruent=1),on=['word','ink'],how='left').fillna(0)

Upvotes: 1

Bharath M Shetty
Bharath M Shetty

Reputation: 30605

I think you are looking for mapping and matching i.e

di = dict(zip(word,ink))
df['new'] = (df['word'].map(di) == df['ink']).astype(int)

    word     ink  new
0   bleu     red    0
1  jaune  yellow    1
2  jaune    blue    0
3  jaune  yellow    1
4   vert    blue    0

Upvotes: 2

Related Questions