Excel表列排序:JSON导出数据如何将相同日期值归入对应列完成转换
表格结构转换实现方案
以下两种方案均可实现需求,可根据数据量和使用习惯选择:
方案1:Excel内置Power Query实现(无代码,适合<10万行的小数据量)
- 选中整张数据区域,点击「数据」选项卡 → 「从表格/范围」,导入Power Query编辑器,确认第一列User为文本类型,其他列保留原有格式。
- 选中「User」列,右键选择「逆透视其他列」,把所有列组的内容转成长表结构,此时会自动生成「属性」(原列名)、「值」两列。
- 提取列组标识和字段类型:添加自定义列,若原列名带有序号后缀(如
date_0、property1_0),可通过Text.BeforeDelimiter([属性], "_")提取字段类型(date/property1/property2/property3),通过Text.AfterDelimiter([属性], "_")提取列组序号。如果原列名没有序号标识,可直接按列的位置生成序号:第2-5列为组0,第6-9列为组1,以此类推即可。 - 筛选掉「值」列为空的行,按列组序号分组,把每个序号对应的date值关联到同组的所有property行上。
- 提取所有不重复的date值,统一转成日期格式后按时间先后排序,为每个date生成3个对应property字段名,格式参考
[date值]_property1。 - 选中「字段类型+date值」组合列做透视,值选择原「值」列,聚合方式选「不要聚合」,空值会自动留空,最终生成按date排序的宽表结构。
- 点击「关闭并上载」即可把转换完成的表格导回Excel。
方案2:Python pandas实现(适合大数据量、需要重复处理的场景)
提前安装依赖:pip install pandas openpyxl
import pandas as pd from collections import defaultdict # 1. 读取源Excel文件,替换为你自己的文件路径 df = pd.read_excel("源数据文件.xlsx") user_col_name = "User" # 2. 遍历提取所有用户、日期和对应属性 user_date_props = defaultdict(dict) all_unique_dates = set() for _, row in df.iterrows(): current_user = row[user_col_name] # 跳过第一列User,每4列为一个组遍历 for group_start_idx in range(1, len(df.columns), 4): date_val = row.iloc[group_start_idx] if pd.isna(date_val): continue # 统一转成标准日期格式,避免排序出错 formatted_date = pd.to_datetime(date_val).strftime("%Y-%m-%d") all_unique_dates.add(formatted_date) # 读取当前date对应的三个property值 p1 = row.iloc[group_start_idx+1] p2 = row.iloc[group_start_idx+2] p3 = row.iloc[group_start_idx+3] # 存入用户对应date的属性字典 user_date_props[current_user][f"{formatted_date}_p1"] = p1 if not pd.isna(p1) else "" user_date_props[current_user][f"{formatted_date}_p2"] = p2 if not pd.isna(p2) else "" user_date_props[current_user][f"{formatted_date}_p3"] = p3 if not pd.isna(p3) else "" # 3. 生成按日期排序的新表头 sorted_dates = sorted(all_unique_dates, key=lambda x: pd.to_datetime(x)) new_header = [user_col_name] for d in sorted_dates: new_header.extend([d, f"{d}_property1", f"{d}_property2", f"{d}_property3"]) # 4. 构建结果表格 result_rows = [] for user, props in user_date_props.items(): current_row = [user] for d in sorted_dates: current_row.append(d) current_row.append(props.get(f"{d}_p1", "")) current_row.append(props.get(f"{d}_p2", "")) current_row.append(props.get(f"{d}_p3", "")) result_rows.append(current_row) result_df = pd.DataFrame(result_rows, columns=new_header) # 5. 导出结果,替换为你想要的输出路径 result_df.to_excel("转换后结果.xlsx", index=False)
如果你的实际表格列组步长不是4,可自行调整range(1, len(df.columns), 4)中的步长和取值偏移量。
内容的提问来源于stack exchange,提问作者Data_Science_110
相关产品推荐
相关产品推荐

