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

Python/Pandas 无法将所有行追加到DataFrame的问题求助

问题原因

  1. 循环内每次覆盖df2变量,之前分组生成的空行全部丢失,最终仅保留最后一个Type对应的空行
  2. 循环内的单独df2语句无任何赋值或拼接操作,属于无效代码
  3. 原代码使用的append方法已被pandas官方弃用,推荐使用pd.concat实现数据拼接

修复后代码

import pandas as pd
import numpy as np

def expander(input_dataframe, n):
    # 存储所有待追加的空行
    append_list = []
    # 遍历所有唯一Type值
    for typ in input_dataframe['Type'].unique():
        # 生成当前Type对应的n行空Variants数据
        temp_df = pd.DataFrame({
            'Type': [typ] * n,
            'Variants': [np.nan] * n
        })
        append_list.append(temp_df)
    # 拼接原数据和所有待追加空行,按Type排序后重置索引
    result = pd.concat([input_dataframe] + append_list, ignore_index=True)\
             .sort_values('Type', ignore_index=True)
    print(result)
    return result

调用测试

expander(input_dataframe=pd.DataFrame({
    'Type':['iPhone', 'iPhone', 'iPhone', 'iPhone', 'Samsung', 'Samsung', 'Samsung', 'Samsung'],
    'Variants':['12 Mini', '12', '12 Pro', '12 Pro Max', 'S21 FE', 'S21', 'S21+', 'S21 Ultra']
}), n = 4)

运行后即可实现预期效果:每个Type分组的原有4条数据后,追加4条Variants为空的行。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 20:54:04