首页 > 解决方案 > 将存储过程转换为 python pandas 代码?

问题描述

要创建的列使用列作者类型进行排名。

例子:

PMID
200 3
201 0
200 0
202 0
200 2
201 1
200 1

预期的 :

PMID 作者类型
200 3 最后作者
201 0 第一作者
200 0 第一作者
202 0 第一作者
200 2 共同作者
201 1 最后作者
200 1 共同作者
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [datacleaning].[pub_set_authors]
AS
BEGIN
    WITH cte AS 
    (
        SELECT 
            *,
            ROW_NUMBER() OVER (PARTITION BY [pub_id] ORDER BY [rank] DESC) AS rnk
        FROM 
            datacleaning.pubmed_details
    )
    UPDATE datacleaning.pubmed_details
    SET author_type = 'Last Author'
    WHERE row_id IN (SELECT row_id
                     FROM cte
                     WHERE rnk = 1)

    UPDATE datacleaning.pubmed_details
    SET author_type = 'First Author'
    WHERE rank = 0;

    UPDATE datacleaning.pubmed_details
    SET author_type = 'Co Author'
    WHERE author_type is NULL;
END

标签: pythonsqlpandasdataframe

解决方案


这得到了上面的结果;要复制row_number over partitionsql 代码中的部分,您可以groupbycumcount. 下一步使用np.select,类似于多个 case-when 表达式:

(df.assign(row_number = df.groupby("PMID").Rank.cumcount(), 
           Author_type = lambda df: np.select([df.Rank == 0, 
                                               df.row_number.isin([0, 1]),  
                                               df.row_number > 1], 
                                              ['First Author', 
                                               'Last Author', 
                                               'Co Author'])
            )
  .drop(columns = 'row_number')
)



   PMID  Rank   Author_type
0   200     3   Last Author
1   201     0  First Author
2   200     0  First Author
3   202     0  First Author
4   200     2     Co Author
5   201     1   Last Author
6   200     1     Co Author

推荐阅读