首页 > 解决方案 > Pandas 中的合并表

问题描述

我正在尝试合并两个不同的表。

表 1 包含 NGS FILE 染色体起始和结束位置和序列

表 2 包含另一个仅包含 Chromosome 和 Pos 的表

我想从表 1 中提取行条件是 Pos 值(表)在表 1 中的 Pos 和 PosEnd 范围内。例如 Pos 57292 在表 2 中,所以我想从表 1 中提取值,其中 57292 在 Pos 和 Pos 之间以表 1 结尾。

表 2 大小约为 50K,表 1 大小为 1000K。谁能分享最快的方法?

手动检查

标签: pythonpandas

解决方案


#I am doing in this way but it takes around 15~20 Minutes, is there any way so i can 
#compute within 10 Minutes

#del final_df
final_df = pd.DataFrame(columns=["Chr", "Pos_start", "Pos_End", "Seq", "Pos"])
start = time.time()

for chr_ in chr_list:
    print("Doing", chr_, end="  --->  ")
    temp_fetal = fetal[fetal.Chr.isin([chr_])]
    temp_mother = mother[mother.Chr.isin([chr_])]

    ## Again loop to all data Frame
    for i in range(len(temp_fetal)):
        #print(i, end="--")
    
        ## Use between Function # !!!!!! *****
        condition = (temp_fetal.iloc[i, :]["Pos"] >= temp_mother.Pos_start) & (
            temp_fetal.iloc[i, :]["Pos"] <= temp_mother.Pos_End)
        if (condition.any()):
            _ = pd.concat([
                temp_mother[condition].reset_index(drop=True),
                temp_fetal.iloc[[i], 1:].reset_index(drop=True)
            ],
                          axis=1)
            final_df = final_df.append(_, ignore_index=True)
#end = time.time()
#process_time = round((end - start)/60 , 2)

推荐阅读