You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决为多个行数不同的Pandas Dataframe补零对齐时代码不生效问题

问题根因
  • 遍历rows_list时拿到的lista是元素的临时副本,对lista的赋值操作仅作用于临时变量,不会修改原列表中存储的DataFrame,这是操作不生效的核心原因
  • 内层循环中重复将lista转为DataFrame属于冗余操作,没有实际作用
  • pandas 1.4及以上版本已废弃append方法,即使调整赋值逻辑也会触发警告,存在版本兼容问题
修复代码
import pandas as pd

rows_list = list(patientdataset.copy().values())
rows_len = [len(df) for df in rows_list]
max_length = max(rows_len)
# 预定义补零行模板,避免循环中重复创建
zero_template = pd.Series([0.0, 0.0, 0.0], index=['Level','IsCorrect','TotalSeconds'])

for idx in range(len(rows_list)):
    current_df = rows_list[idx]
    need_pad = max_length - len(current_df)
    if need_pad <= 0:
        continue
    # 一次性构造所有补零行并拼接,直接赋值回原列表对应索引位置
    pad_df = pd.DataFrame([zero_template]*need_pad)
    rows_list[idx] = pd.concat([current_df, pad_df], ignore_index=True)
验证方法

执行完成后打印所有DataFrame的长度即可确认是否生效:

print([len(df) for df in rows_list])

内容的提问来源于stack exchange,提问作者Paulo Costa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 21:06:03