首页 > 解决方案 > 如何根据 ID 合并两个大型 Pandas 数据帧 - 通过块读取最大的文件?

问题描述

我有两个 CSV 文件,df1_50GB.csv 和 df2_1GB.csv。我想根据匹配的 ID 值合并数据框。这是我到目前为止所做的

f50GB =  "df1_50GB.csv"
f1GGB =  "df1_1GGB.csv"
result_file =  "output.csv"

tmp50GB = pd.read_csv(f50GB, nrows=3)
tmp1GB = pd.read_csv(f1GGB, nrows=3)

# creating an empty bucket to save result
df_result = pd.DataFrame(columns=(tmp50GB.columns.append(tmp1GB.columns)).unique())
df_result.to_csv(result_file, index_label=False)
tmp1GB = pd.read_csv(f1GGB)
# Save (append) data which the ID of f1GB  mached with f50GB i.e (x)  #
def save_merged_csv(x):
    df = pd.merge(x, tmp1GB, on='ID', how='left')
    df.to_csv(result_file, mode="a", header=False, index=False)


# create the iterator
csv_reader = pd.read_csv(
    f50GB,
    iterator=True,
    chunksize=100000)

[save_merged_csv(r) for r in csv_reader]

但我不断收到错误“TypeError:只能合并 Series 或 DataFrame 对象,a 已通过”[更新]该错误现已修复。感谢@Michael Gardner。但我不确定逻辑是否正确。结果的文件大小太大。它也很慢。所以,如果有改进的余地,我会把它留在这里。

标签: python-3.xpandas

解决方案


推荐阅读