Python pandas 中的嵌套情况

问题描述 投票:0回答:1

有一个包含多个嵌套case when语句的sql代码如下:

select case when t1.marks is null and t1.country in ctry_list
then case when t1.class='maths' 
          then (select t2.marks*5 from table2 t2 where t2.class='algebra' 
                and t2.country=t1.country) end else t1.marks end as new_marks
from table1 t1

目的是将这个sql代码转换为pandas语法

python sql pandas dataframe
1个回答
0
投票

对于 Pandas 框架中的转换,

apply
函数可以与实现嵌套条件的用户定义函数一起使用。

# function to apply the nested conditions
def calculate_new_marks(row):
    if pd.isnull(row['marks']) and row['country'] in ctry_list:
        if row['class'] == 'maths':
            algebra_marks = df2.loc[(df2['class'] == 'algebra') & (df2['country'] == row['country']), 'marks'].values
            return algebra_marks[0] * 5 if len(algebra_marks) > 0 else None
    return row['marks']
© www.soinside.com 2019 - 2024. All rights reserved.