Take values from a column of a dataframe and create a column in another with the corresponding values

Asked

Viewed 938 times

2

I have two df1 and df2 dataframes, both have team column, but only df2 have the numeral column that every day changes, wanted the values of the numeral column to turn a column in df1, but always in front of the responsible team

example:

df1:
equipe
a
b
b
a
c
a
b

df2:
equipe   numeral
a           1
b           2
c           3

wanted df1 to stay:

df1:
equipe    numeral
a            1
b            2
b            2
a            1 
c            3
a            1
b            2

I used this code, but it generates an entire empty column

def comunidade(num):
    if num == 'a':        
        return def2.loc[index, 'def2']
    elif num == 'b':
        return def2.loc[index, 'def2']
    elif num == 'c':
        return def2.loc[index, 'def2']

df1['numeral'] = df2['numeral'].map(comunidade)

1 answer

2


You can do it using the method merge, specifying the column where to do the join (in this case the equipe)

df1 = df1.merge(df2, on='equipe', how='left')
  • It worked perfectly, thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.