简体   繁体   English

这是关于python中的一个简单代码

[英]This is regarding a simple code in python

I have two tables here我这里有两张桌子

 Reg_No     Name  Marks Grade  Sub1  Sub2
     1  Sanjana    100    A1  60.0   NaN
     2    Alfaz     70     A   NaN  65.0
     3     Ritu     50     B  30.0   NaN
     4    Priya     60     A   NaN  40.0

        Sub1  Sub2
IA      0.50  0.40
OA      0.50  0.60
Others  0.25  0.25

The first table contains marks , sub1 and sub2 and the second table contains IA , OA , Others as rows based on the subjects.第一个表包含markssub1sub2 ,第二个表包含IAOAOthers作为基于主题的行。

I need to split the column Marks of the first table based on the second table into 3 new columns.我需要将基于第二个表的第一个表的列Marks拆分为 3 个新列。 The first column is the IA column, if its sub1 in the first table, it should split based on the sub1 column of second table第一列是IA列,如果它在第一个表中的sub1 ,则应该根据第二个表的sub1列进行拆分

example:例子:

IA = table1.marks*table2(IA)(sub1) 

ie 100*0.50100*0.50

This should be my output这应该是我的输出

Reg_No  Name    Marks   Grade   Sub 1   Sub 2   IA_ OA_ Others_
1   Sanjana       100    A1     60              50  50  25
2   Alfaz         100    A              65      40  60  25
3   Ritu          100    B      30              50  50  25
4   Priya         100    A              40      40  60  25

Please tell me how to code for this请告诉我如何为此编码

I get every row from second DataFrame and use it with apply() to create new column in first DataFrame我从第二个DataFrame获取每一行并将其与apply()一起使用以在第一个DataFrame创建新列

import pandas as pd
import io

text = '''Marks  Sub1  Sub2
100    60.0  NaN
70     NaN   65.0
50     30.0  NaN
60     NaN   40.0'''
df1 = pd.read_csv(io.StringIO(text), sep='\s+')

text = '''Sub1  Sub2
IA      0.50  0.40
OA      0.50  0.60
Others  0.25  0.25'''
df2 = pd.read_csv(io.StringIO(text), sep='\s+')

for row in df2.itertuples():
    name, sub1, sub2 = row  
    df1[name] = df1.apply(lambda x: (x['Marks']*sub2) if pd.isna(x['Sub1']) else (x['Marks']*sub1), axis=1)

print(df1)

Result:结果:

   Marks  Sub1  Sub2    IA    OA  Others
0    100  60.0   NaN  50.0  50.0    25.0
1     70   NaN  65.0  28.0  42.0    17.5
2     50  30.0   NaN  25.0  25.0    12.5
3     60   NaN  40.0  24.0  36.0    15.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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