如何将具有不同列中的多组数据的行拆分为多行

How to split a row with multiple sets of data in different columns into mutiple rows

大家好!我对从现场收集的数据有疑问,其中每一行在不同列中都有多组数据(参见输入)。我尝试将每组数据拆分成一行(见预期输出)。

输入:

行 1:ID A1 B1 C1 D1 A2 B2 C2 D2 A3 B3 C3 D3 A4 B4 C4 D4 姓名 1 姓名 2 姓名 3 姓名 4 日期

预期输出:

行 1:ID A1 B1 C1 D1 姓名 1 日期

第 2 行:ID A2 B2 C2 D2 姓名 2 日期

第 3 行:ID A3 B3 C3 D3 姓名 3 日期

第 4 行:ID A4 B4 C4 D4 姓名 4 日期

我发现有一个类似的 ,但它使用的是 VBA 脚本。我是一个 GIS 人,我对 python 的 ArcPy 站点包有一些经验。我在使用 ArcPy 构建逻辑工作流时遇到了一些问题。我想知道是否有人遇到过类似情况并且知道是否可以使用 Python 和 ArcPy 或任何其他站点包来完成。如果是这样,能否请您提供一些提示,说明我应该研究哪些网站包和工具?

使用 arcpy 执行此操作的方法是使用游标。 创建一个新的 table,遍历您的数据,拆分它们并将每一行插入新的 table.

这是使用 ArcMap 中的 arcpy(不是 ArcGIS Pro):

import arcpy
import os

src_data = ''  # Path to your data
dst_data = ''  # New table that will be create. 
arcpy.CreateTable_management(os.path.dirname(dst_data),
                             os.path.basename(dst_data))

# Create the correct fields in the new table
# Assuming the fields have the same name as your data in Row1
# Also assuming the A1, A2, A3 fields .... have the same type/scale/precision/length/etc
# Index split table (index from the Row1 you gave in your example)
dst_idx_split = [[0, 1, 5, 9, 13, 17, 21],  # ID A1 B1 C1 D1 Name1 Date
                 [0, 2, 6, 10, 14, 18, 21], # ID A2 B2 C2 D2 Name2 Date
                 [0, 3, 7, 11, 15, 19, 21], # etc.
                 [0, 4, 8, 12, 16, 20, 21]]

src_fields = arcpy.ListFields(src_data)
for idx in dst_idx_split[0]:
    field = src_fields[idx]
    field_name = field.baseName if field_name in ['ID', 'Data'] else field_name[:-1]  # remove the 1/2/3/4 in the field name
    arcpy.AddField_management(dst_data, field_name, field.type, field.precision, 
                              field.scale, field.length, field.alias, 
                              field.isNullable, field.required, field.domain)

# Copy the data
i_cur = arcpy.da.InsertCursor(dst_data, '*')

with arcpy.da.SearchCursor(src_data, '*') as s_cur:
    for row in s_cur:  # for each row of your source data
        for idxs in dst_idx_split: 
            dst_row = [row[idx] for idx in idxs] # extract the data for the new line 
            i_cur.insertRow(dst_row)  # insert it in new table
del i_cur