创建一个包含一组 CSV 中唯一值的极坐标数据框

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

我有超过 3000 个 CSV,其中有超过 10 列。我需要的是从其中两个中获取所有独特的值。我能够读取极坐标中的独特值:

import polars as pl

df1 = pl.read_csv("test1.biobank.tsv.gz", separator='\t', schema_overrides={"#chrom": pl.String}, n_threads=8, columns=["#chrom", "pos"], new_columns=["chr", "pos"]).unique()

我可以将剩下的文件一一读取,即:

df2 = pl.read_csv("test2.biobank.tsv.gz", separator='\t', schema_overrides={"#chrom": pl.String}, n_threads=8, columns=["#chrom", "pos"], new_columns=["chr", "pos"]).unique()

检查所有值是否不相等:

if not df1.equals(df2):
    df = df1.vstack(df2)
    del(df1)
    del(df2)  

然后

.unique()
。但由于所有输入文件都已在两列(chr、pos)上排序,并且 16M 输入行中的差异有数千个,我希望有更好的方法来做到这一点。

感谢您提前的帮助

DK

编辑

还有另一种使用 Polars 和 DuckDB 的方法。

  • 为每个输入创建镶木地板文件
tsv_pattern = "gwas_*.gz"

for fn in glob.glob(tsv_pattern):
    print(fn)
    parquet_fn = fn.replace(".gz", ".chr_pos.parquet")
    df = pl.read_csv(fn, separator='\t', schema_overrides={"#chrom": pl.Utf8}, n_threads=8, columns=["#chrom", "pos"], new_columns=["chr", "pos"]).unique()
    df.to_parquet(parquet_fn, compression='zstd')
    del(df)

  • 运行 duckdb 并执行:
CREATE TABLE my_table AS SELECT DISTINCT * FROM 'my_directory/*.parquet'

感谢 DuckDB 的 Mark Mytherin

python python-polars duckdb
1个回答
2
投票

您可以使用 glob 模式读取 csv,然后调用

unique

(pl.scan_csv("**/*.csv")
 .unique()
 .collect())
© www.soinside.com 2019 - 2024. All rights reserved.