简体   繁体   中英

Fill cell within a dataframe according to another in pandas

I have two dataframes such as

Tab1:

ORFs_values      Groups       SP1  SP2   SP3
SP_ORF1          Group1       1    1     0
SP_ORF1          Group2       0    0     0
SP_ORF1          Group3       0    1     0
SP_ORF1          Group4       1    1     1

and another:

Tab2

Groups         SP_names   SP_names2
Group1         SP1        SP1_A
Group1         SP2        SP2_A
Group3         SP2        SP2_BL
Group4         SP1        SP1_BI
Group4         SP2        SP2_OP
Group4         SP3        SP3_I

And I would like to replace within the Tab1 all cells with 1, and with their corresponding SP_names2 for each matching Groups and SP_names .

For instance, in the first row of Tab1 , the SP_names2 value for SP1 in Group1 is SP1_A , so I replace 1 by SP1_A and so on...

I should then get the following output:

New_tab1:

ORFs_values      Groups       SP1      SP2       SP3
SP_ORF1          Group1       SP1_A    SP2_A     0
SP_ORF1          Group2       0         0        0
SP_ORF1          Group3       0         SP2_BL   0
SP_ORF1          Group4       SP1_BI    SP2_OP   SP3_I

Here are the two df in dict format if it can help:

Tab1

{'ORFs_values': {0: 'SP_ORF1', 1: 'SP_ORF1', 2: 'SP_ORF1', 3: 'SP_ORF1'}, 'Groups': {0: 'Group1', 1: 'Group2', 2: 'Group3', 3: 'Group4'}, 'SP1': {0: 1, 1: 0, 2: 0, 3: 1}, 'SP2': {0: 1, 1: 0, 2: 1, 3: 1}, 'SP3': {0: 0, 1: 0, 2: 0, 3: 1}}

Tab2

{'Groups': {0: 'Group1', 1: 'Group1', 2: 'Group3', 3: 'Group4', 4: 'Group4', 5: 'Group4'}, 'SP_names': {0: 'SP1', 1: 'SP2', 2: 'SP2', 3: 'SP1', 4: 'SP2', 5: 'SP3'}, 'SP_names2': {0: 'SP1_A', 1: 'SP2_A', 2: 'SP2_BL', 3: 'SP1_BI', 4: 'SP2_OP', 5: 'SP3_I'}}

Here is a solution using mask()

df is Tab1 and df2 is Tab2

df = df.set_index('Groups')
(df.mask(df.eq(1),
         df2.set_index(['Groups','SP_names'])['SP_names2'].unstack())
 .reset_index())

Output:

   Groups ORFs_values     SP1     SP2    SP3
0  Group1     SP_ORF1   SP1_A   SP2_A      0
1  Group2     SP_ORF1       0       0      0
2  Group3     SP_ORF1       0  SP2_BL      0
3  Group4     SP_ORF1  SP1_BI  SP2_OP  SP3_I

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM