Pandas dataframe create a new column based on the columns of other data frames

So, I have these two df:
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 with respect to 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'm making more mistakes. Hope someone can help me. Thanks in advance.

+5
source share
1 answer

You can use a 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 
+3
source

Source: https://habr.com/ru/post/1265524/


All Articles