Using column headings and values ​​from one data frame to find weights in another piece of data

I have two tables that look like this

ID param1 param2 param3 0 A12 2 1 1 1 B15 1 2 1 2 B20 2 2 1 ... 

and

  parameter value weight 0 param1 1 10 1 param1 2 13 2 param2 1 21 3 param2 2 39 4 param3 1 49 5 param3 2 61 

What is the best way to take the first data frame, find each parameter weight in the second data frame and return the data frame as shown below?

  ID param1 param2 param3 0 A12 13 21 49 1 B15 10 39 49 2 B20 13 39 49 

What I was thinking about is to write the function specified by the parameter and the value, a subset of table2, as shown below, table2[(table2['parameter'] = parameter) & (table2['value'] = value)] and do some kind of vector application for each column in table1, but I'm not sure how to go through each value and do a search.

+5
source share
2 answers

One option would be to convert table1 to long format, merge with table2 by parameters and values, and then convert it to wide format:

 In [85]: pd.merge(pd.melt(df1, id_vars='ID'), df2, left_on=['variable', 'value'], right_on=['parameter', 'value'] ).pivot('ID', 'parameter', 'weight') Out[85]: parameter param1 param2 param3 ID A12 13 21 49 B15 10 39 49 B20 13 39 49 
+5
source

A bunch of fainting, and I came up with something far from @Psidom. I only convinced myself to publish in order to give some idea of ​​getting into the same solution with different methods.

 In [55]: (df1.set_index('ID') .rename_axis('parameter', 1) .stack() .reset_index(name='value') .merge(df2) .set_index(['ID', 'parameter']).weight.unstack()) Out[55]: parameter param1 param2 param3 ID A12 13 21 49 B15 10 39 49 B20 13 39 49 
+2
source

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


All Articles