第四章: 多表的合并(merge, append的使用)

第四章: 多表的合并(merge, append的使用)

字段方向上的拓展(更多列) — merge

import pandas as pd
filepath_01 = r"file01.xlsx"
filepath_02 = r"file02.xlsx"
df_table_01 = pd.read_excel(filepath_01)
df_table_02 = pd.read_excel(filepath_02)

# merge()会将两张表中所有的字段都保留下来, 同名属性会添加后缀, 默认是_x, _y 
# 手动选择需要保留的列, 假设第一张表的字段名为x1, x2, x3; 第二张表的字段为y1, y2, y3
need_column = ["x1", "x2", "y1", "y2"]
df_table_merge = pd.merge(left = df_table_01, right = df_table_02, #left和right分别表示要合并的两张表
		 				  left_on = ["x3"], right_on = ["y3"], #left_on和right_on分别表示两张表中具有相同含义的字段, 根据该条件进行连接. 因为不同表中相同含义的字段的命名可能不一致
		 				  how = "left", #表示左外连接, 即当左表中的left_on字段在右表的right_on字段中无法对应时, 会保留左表中的数据. 也是默认左表作为主表
		 				  suffixes = ("_delete", "")) # 对同名字段添加后缀的规则进行修改, 默认右表中有着左表中需要的字段数据, 因此将左表中的同名字段的后缀命名为_delete, 方便后面进行筛选
result = df_table_merge[need_column] # 根据前面手动选择的列名来去除掉冗余数据

元组方向的拓展(更多行) — append

import pandas as pd
filepath_01 = r"file01.xlsx"
filepath_02 = r"file02.xlsx"
df_table_01 = pd.read_excel(filepath_01)
df_table_02 = pd.read_excel(filepath_02)

# 注意保持列名一致, 追加后进行赋值替换, 否则不生效 
df_table_01 = df_table_01.append(df_table_02, ignore_index = True)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
-- coding: utf-8 -- import arcpy arcpy.env.overwriteOutput = True # 输入参数 input_feature_class = arcpy.GetParameterAsText(0) # 输入要素类 join_feature_class = arcpy.GetParameterAsText(1) # 连接要素类 output_feature_class = arcpy.GetParameterAsText(2) # 输出要素类 join_fields = arcpy.GetParameterAsText(3) # 连接字段 merge_fields = arcpy.GetParameterAsText(4) # 合并字段 min_area = arcpy.GetParameter(5) # 最小面积 # 创建空间连接 arcpy.SpatialJoin_analysis(input_feature_class, join_feature_class, output_feature_class, "JOIN_ONE_TO_MANY", "", "", "INTERSECT") # 创建输出要素类的字段列表 field_list = [f.name for f in arcpy.ListFields(output_feature_class)] # 创建合并字段的字典 merge_dict = {} # 遍历输出要素类中的要素 with arcpy.da.UpdateCursor(output_feature_class, field_list) as cursor: for row in cursor: # 如果要素面积大于最小面积,则进行合并 if row[0] > min_area: # 创建合并字段的键值 merge_key = tuple([row[field_list.index(f)] for f in merge_fields.split(";")]) # 如果合并字段的键值不存在,则添加到字典中 if merge_key not in merge_dict: merge_dict[merge_key] = [] # 将当前要素的连接字段值添加到字典中 join_values = [row[field_list.index(f)] for f in join_fields.split(";")] merge_dict[merge_key].append(join_values) # 删除不符合条件的要素 else: cursor.deleteRow() # 遍历合并字段的字典,将连接字段的值合并并更新到输出要素类中 with arcpy.da.UpdateCursor(output_feature_class, merge_fields.split(";")) as cursor: for row in cursor: merge_key = tuple(row) if merge_key in merge_dict: join_values = merge_dict[merge_key] join_values = ["/".join([str(v) for v in j]) for j in join_values] row = tuple(join_values) cursor.updateRow(row)运行错误:IndentationError: unexpected indent (空间连接.py, line 18) 执行(空间连接多对一)失败。请改正代码
05-25
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值