python - 将存储过程转换为 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
解决方案
这得到了上面的结果;要复制row_number
over
partition
sql 代码中的部分,您可以groupby
与cumcount
. 下一步使用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
推荐阅读
- python - 从数据框中创建逗号分隔列表以传递到 SQL 查询时出错
- docker - Dockerfile 环境变量
- mysql - 从远程机器通过 SSH 的 Docker 命令
- mysql - 如何从 MySQL 中的比较和空检查中指定 ORDER BY?
- sql-server - SQL Server:多部分标识符子查询
- angular - 动态扩展行 ng2-smart-table Angular
- javascript - Firefox 浏览器上带有时区错误的 JavaScript 日期对象
- android - 为什么我无法从 Android Work Profile 中实际存在的路径创建文件?
- java - 将图像上传到 Firebase 时,如何创建将下载 URL 作为字符串返回的方法
- angular - 如何使用 jest 和可选的弹珠测试复杂的 ngrx/rxjs 服务