简体   繁体   中英

Access some constant value attached to some rows in dataframe1 and use the value in dataframe2

I have two dataframes.

data1 = 

index   comp    D   F   G   Q
0       T1      1   3   4   0.50
1       T2      2   3   2   0.75
2       T3      4   7   7   0.80
3       T4      5   6   7   0.21
4       T5      6   9   0   0.61

data2 = 

index   ID   T1   T2    T3   T4   T5
0       Q1   100  121   43   56   78
1       Q2   23   43    56   76   87
2       Q3   345  56    76   78   98
3       Q4   21   32    34   45   56
4       Q5   45   654   567  78   90
5       Q6   123  32    45   56   67

Now I want to create a DataFrame that basically replaces the cell values of data2 for T1,T2,T3,T4,T5 but column 'ID' remains intact.

the value is replaced by the (current cell value from data2 )*( 'Q' value of the particular 'comp')

say the '100' under T1 in data2 is replaced by 100*0.5 = 50 ; '121' under T2 in data2 is replaced by 121*0.75 = 90.75 ;

The thing is that I just want to access the 'Q' value attached to each 'comp' in data1 and use it in another dataframe.

How to do this??

data2[['T1','T2','T3','T4','T5']] *= (data1.set_index('comp').Q)


index   ID  T1      T2      T3      T4      T5
0   0   Q1  50.0    90.75   34.4    11.76   47.58
1   1   Q2  11.5    32.25   44.8    15.96   53.07
2   2   Q3  172.5   42.00   60.8    16.38   59.78
3   3   Q4  10.5    24.00   27.2    9.45    34.16
4   4   Q5  22.5    490.50  453.6   16.38   54.90
5   5   Q6  61.5    24.00   36.0    11.76   40.87

I would do it this way:

cols = [x for x in list(df_2) if x.startswith('T')]
for i in cols:
    df_2[i] = df_2[i] * df[df['comp'] == i]['Q'].max()
print(df_2)

Output:

   index     T1     T2    T3     T4     T5
0      0   50.0  90.75  34.4  11.76  47.58
1      1   11.5  32.25  44.8  15.96  53.07
2      2  172.5  42.00  60.8  16.38  59.78

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