123456789101112131415161718192021222324252627282930 |
- import pandas as pd
- import numpy as np
- df_1 = pd.read_excel(r"D:\guozhong\19、定远县\19、定远县\定远县剖面数据统计20241222.xlsx",converters={'原样品编号': str})
- df_1
- df_2 = pd.read_excel(r"D:\guozhong\19、定远县\19、定远县\定远县土壤容重.xlsx",converters={'原样品编号': str})
- df_2
- # 确保列为字符串类型
- df_1["原样品编号"] = df_1["原样品编号"].astype(str)
- df_2["样品编号"] = df_2["样品编号"].astype(str)
- # 提取前16位和最后1位并组合
- df_1["原样品编号前16位"] = df_1["原样品编号"].str[:16] + df_1["原样品编号"].str[-1]
- df_2["样品编号前16位"] = df_2["样品编号"].str[:16] + df_2["样品编号"].str[-1]
- # 合并表格(左连接,保留df_1中的所有数据)
- merged_df = pd.merge(
- df_1,
- df_2[["样品编号前16位", "土壤容重1(g/cm³)", "土壤容重2(g/cm³)", "土壤容重3(g/cm³)", "土壤容重4(g/cm³)", "土壤容重平均值(g/cm³)"]],
- left_on="原样品编号前16位",
- right_on="样品编号前16位",
- how="left"
- )
- # 删除辅助列
- merged_df = merged_df.drop(columns=["原样品编号前16位", "样品编号前16位"])
- # 输出结果
- print(merged_df)
- merged_df.to_excel(r"定远剖面容重.xlsx", index=False, engine="openpyxl")
|