polars 长转宽

import polars as pl

# pl.show_versions()

yg = pl.read_excel("/mnt/c/Users/xuefliang/Downloads/乙肝.xlsx").with_columns(
    pl.col("有效证件号").str.strip_chars("'"),
    pl.col('卡片ID').str.strip_chars("'")

) 


jz=(

    jz.sort('jz_sj')
    .with_columns(
        pl.col('grda_et_lsh')
        .cum_count()
        .over('grda_et_lsh')
        .alias('jc')
    )
)


#pivot 长转宽
jz = (
    pl.read_database_uri(query=query, uri=uri)
    .rename(lambda col:col.lower())
    .with_columns(pl.col("jz_zc").cast(pl.Int32))
    .pivot(index="zjhm", on="jz_zc", values="jz_sj", aggregate_function="first")
)

(
    yg.select(
        pl.concat_str([pl.lit("'"), pl.col('有效证件号'), pl.lit("'")])
    )
    .write_csv('/mnt/c/Users/xuefliang/Downloads/test.txt')
)

result = yg.select(
    (pl.lit("'") + pl.col('有效证件号') + pl.lit("'")).alias('有效证件号')
)

# 转换为列表并手动写入
with open('/mnt/c/Users/xuefliang/Downloads/test.txt', 'w') as f:
    data = result['有效证件号'].to_list()
    for i, item in enumerate(data):
        if i < len(data) - 1:
            f.write(item + ',\n')
        else:
            f.write(item)  # 最后一行不加逗号

评论

此博客中的热门博文

V2ray websocket(ws)+tls+nginx分流

Rstudio 使用代理