Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 429
Gunnar Avatar asked Oct 18 '22 15:10

Gunnar


1 Answers

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
like image 131
Vaishali Avatar answered Oct 20 '22 09:10

Vaishali