如何基于表头对CSV文件数据排序生成标准化输出,并实现INPUT OUTPUT场景下的交易归属自动分配?
Hey there! Let's tackle your two CSV processing needs with clear, actionable code and explanations.
一、读取CSV表头并按表头排序数据
First up, reading CSV headers and sorting data based on those headers. Here are two straightforward approaches depending on your tool preference:
方法1:使用Python原生csv模块
If you want to stick to built-in tools without external libraries:
import csv # 读取CSV文件 with open('your_file.csv', 'r') as f: reader = csv.reader(f) # 获取表头 headers = next(reader) # 按表头字母顺序排序(也可以自定义排序规则) sorted_headers = sorted(headers) # 建立表头与索引的映射,方便后续重排每行数据 header_indices = {header: idx for idx, header in enumerate(headers)} # 处理每行数据,按排序后的表头重新排列 sorted_rows = [] for row in reader: sorted_row = [row[header_indices[h]] for h in sorted_headers] sorted_rows.append(sorted_row) # 输出标准化结果(示例为写入新CSV) with open('sorted_output.csv', 'w', newline='') as f: writer = csv.writer(f) writer.writerow(sorted_headers) writer.writerows(sorted_rows)
Note: 如果需要自定义排序顺序而非字母序,直接把sorted(headers)替换成你预设的表头列表即可(比如['Name', 'Date', 'Amount'])。
方法2:使用pandas(更简洁高效)
For a faster, more concise solution, pandas is your go-to:
import pandas as pd # 读取CSV文件 df = pd.read_csv('your_file.csv') # 按表头字母顺序排序列(axis=1表示按列方向排序) sorted_df = df.reindex(sorted(df.columns), axis=1) # 输出标准化结果(index=False避免写入额外索引列) sorted_df.to_csv('sorted_output.csv', index=False)
几行代码就搞定所有繁琐操作!
二、拆分同一列的人员信息并分类交易
Now for the trickier task: splitting Rahul and Ritu's transactions from the same column, plus separating international/domestic transactions. Here's a step-by-step implementation using Python's csv module:
核心逻辑
- 遍历CSV的每一行数据;
- 当遇到包含"Rahul"或"Ritu"的行时,更新
current_user变量,标记后续交易归属的用户; - 当遇到交易类型标识("International transactions"或"Domestic transactions")时,更新
current_transaction_type变量; - 对于普通交易行,结合当前的用户和交易类型,将数据归类到对应位置;
- 最后整理成标准化的结构化数据输出。
代码实现
import csv # 初始化存储结果的字典,预设用户和交易分类 user_transactions = { 'Rahul': {'International': [], 'Domestic': []}, 'Ritu': {'International': [], 'Domestic': []} } current_user = None current_transaction_type = None with open('transactions.csv', 'r') as f: # 使用DictReader可以直接通过列名访问数据,更直观 reader = csv.DictReader(f) for row in reader: # 假设用户标识在'Description'列,根据实际CSV结构调整列名 description = row['Description'].strip() # 识别当前用户 if 'Rahul' in description: current_user = 'Rahul' current_transaction_type = None elif 'Ritu' in description: current_user = 'Ritu' current_transaction_type = None # 识别当前交易类型 elif 'International transactions' in description: current_transaction_type = 'International' elif 'Domestic transactions' in description: current_transaction_type = 'Domestic' # 若已明确用户和交易类型,且当前行是有效交易数据(存在金额列) elif current_user and current_transaction_type and row['Amount']: # 整理交易数据,按需提取需要的字段 transaction = { 'Date': row['Date'], 'Amount': row['Amount'], 'Merchant': row['Merchant'] } # 将交易数据归类到对应位置 user_transactions[current_user][current_transaction_type].append(transaction) # 输出标准化结果(示例为打印,也可写入CSV) for user, categories in user_transactions.items(): print(f"--- {user}'s Transactions ---") for trans_type, transactions in categories.items(): print(f"\n{trans_type}:") for idx, trans in enumerate(transactions, 1): print(f"{idx}. Date: {trans['Date']}, Amount: {trans['Amount']}, Merchant: {trans['Merchant']}")
关键说明
- 请根据你的实际CSV结构,调整代码中的列名(比如
'Description'、'Amount'); - 如果用户/交易类型的标识在其他列,只需修改对应列名的判断逻辑即可;
- 代码逻辑默认:用户标识后,所有后续交易(直到下一个用户标识)都归属于该用户;交易类型标识后,所有后续交易(直到下一个类型标识)都归属于该类型。
内容的提问来源于stack exchange,提问作者Pallav Vyas

