如何用Pandas统计CSV中Fee列数量并生成动态入库数据?
解决动态Fee列生成slot_fee数组的Pandas实现
核心思路
先识别CSV中所有以Fee_开头的列,提取它们的编号(比如Fee_1对应编号1),再匹配同编号的Start_*和End_*列,逐行将这三列的值组装成字典,最终拼接成目标数组。
完整代码示例
import pandas as pd # 1. 读取目标CSV文件 df = pd.read_csv("your_file.csv") # 2. 筛选所有Fee列并解析对应编号 fee_cols = [col for col in df.columns if col.startswith("Fee_")] # 提取编号并转为整数,方便匹配对应Start/End列 fee_numbers = [int(col.split("_")[-1]) for col in fee_cols] # 3. 定义单行数据的slot_fee生成函数 def build_slot_fee(row): slot_fee_arr = [] for num in fee_numbers: # 拼接对应编号的列名 start_col = f"Start_{num}" end_col = f"End_{num}" fee_col = f"Fee_{num}" # 跳过空值组(可根据业务需求调整) if pd.notna(row[start_col]) and pd.notna(row[end_col]) and pd.notna(row[fee_col]): slot_fee_arr.append({ "start": row[start_col], "end": row[end_col], "fee": row[fee_col] }) return slot_fee_arr # 4. 为每行生成slot_fee数组并新增为DataFrame列 df["slot_fee"] = df.apply(build_slot_fee, axis=1) # 5. 后续入库操作示例(以SQLAlchemy为例) # from sqlalchemy import create_engine # engine = create_engine("你的数据库连接字符串") # df.to_sql("目标表名", engine, if_exists="replace", index=False)
关键细节说明
- 列匹配规则:代码默认
Start_*、End_*、Fee_*按编号严格对应,若你的列命名规则不同,只需调整start_col、end_col的拼接逻辑即可。 - 空值处理:代码中加入了空值判断,避免无效数据进入数组,若业务允许空值,可直接移除该判断。
- 性能优化:如果数据量极大,
apply效率不足,可改用itertuples提速:
def build_slot_fee_fast(row): slot_fee_arr = [] for num in fee_numbers: start = row[f"Start_{num}"] end = row[f"End_{num}"] fee = row[f"Fee_{num}"] if pd.notna(start) and pd.notna(end) and pd.notna(fee): slot_fee_arr.append({"start": start, "end": end, "fee": fee}) return slot_fee_arr df["slot_fee"] = [build_slot_fee_fast(row) for row in df.itertuples(index=False)]
内容的提问来源于stack exchange,提问作者rovoda
相关产品推荐
相关产品推荐

