Gunnar
Gunnar

Reputation: 105

Pandas dataframe create a new column based on columns of other dataframes

So I have these two df's:
df A:

ID  TYPE  
1    A
2    B
3    C
4    A
5    C

df B:

TYPE  MEASURE
A      0.3
B      0.4
C      0.5

What I would like to do is add a third column to df A based on the correspondence of df B regarding TYPE:

ID  TYPE MEASURE
1    A     0.3
2    B     0.4
3    C     0.5
4    A     0.3
5    C     0.5

I tried this code:

def operation (row):  

RESULT=B.loc[titlevar['TYPE'] == row['TYPE'] ][['MEASURE']].values  
return RESULT

A['MEASURE'] = A.apply (lambda row: operation (row),axis=1)

But I think I am making more mistakes. Hopefully somebody can help me. Thanks in advance.

Upvotes: 5

Views: 473

Answers (1)

Vaishali
Vaishali

Reputation: 38415

You can use map for this

dfA['MEASURE'] = dfA['TYPE'].map(dfB.set_index('TYPE')['MEASURE'])

dfA:

    ID  TYPE    MEASURE
0   1   A       0.3
1   2   B       0.4
2   3   C       0.5
3   4   A       0.3
4   5   C       0.5

Upvotes: 3

Related Questions