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

如何在Python DataFrame中为每个客户后添加空行?

在DataFrame中为每个客户分组后添加空行

原始DataFrame结构

df1:
Customer         Manager           Time Period      Amount
Samsung     Rosalie             90D     46726190
Samsung     Rosalie             18M     46726190
Samsung     Rosalie             18M     46726190
Samsung     Rosalie             18M     46726190
Samsung     Rosalie             30D     46726190
Samsung     Rosalie             30D     46726190
Apple       Abir                24M     359233179
Apple       Abir                30D     359233179
Apple       Abir                30D     25000000
Nokia       Abir                90D     571711209
Nokia       Abir                24M     571711209
Nokia       Abir                24M     -284461
Nokia       Abir                1M      571711209
Nokia       Abir                1M      49715539
Google      Michael             90D     49850165
Google      Michael             12M     49850165
Google      Michael             12M     49850165
Google      Michael             12M     33048028
Google      Michael             12M     49850165
Google      Michael             12M     33048028
Blackberry  Zec             90D     27975518
Blackberry  Zec             18M     27975518
Blackberry  Zec             30D     27975518
Blackberry  Zec             30D     27975518

期望输出

在每个客户的所有行之后添加一行空行,示例如下:

df1:
Customer         Manager    Time Period Amount
Samsung     Rosalie Navarrete   90D     46726190
Samsung     Rosalie Navarrete   18M     46726190
Samsung     Rosalie Navarrete   18M     46726190
Samsung     Rosalie Navarrete   18M     46726190
Samsung     Rosalie Navarrete   30D     46726190
Samsung     Rosalie Navarrete   30D     46726190

Apple       Abir Paul           24M     359233179
Apple       Abir Paul           30D     359233179
Apple       Abir Paul           30D     25000000

Nokia       Abir Paul           90D     571711209
Nokia       Abir Paul           24M     571711209
Nokia       Abir Paul           24M     -284461
Nokia       Abir Paul           1M      571711209
Nokia       Abir Paul           1M      49715539

Google      MichaelZec          90D     49850165
Google      MichaelZec          12M     49850165
Google      MichaelZec          12M     49850165
Google      MichaelZec          12M     33048028
Google      MichaelZec          12M     49850165
Google      MichaelZec          12M     33048028

用户尝试的错误代码

for index, row in df.iterrrows():
    if df.loc[index,'Customer Code'] != df.loc[index+1,'Customer Code'] and not(pd.isna(df.iloc[index,'Customer Code'])) and not(pd.isna(df.iloc[index+1,'Type']))
        df.loc[index+1] = pd.Series([np.nan,np.nan, np.nan, np.nan])

错误分析

  • 拼写错误:iterrrows 应为 iterrows
  • 列名不匹配:原始DataFrame无Customer Code和Type列,正确列名是Customer
  • 索引越界:处理最后一行时index+1会超出DataFrame范围
  • 循环中直接修改DataFrame会导致索引混乱

正确实现方法

方法一:分组拼接空行

按Customer分组,给每个分组后追加一行全NaN的空行,最后合并所有分组:

import pandas as pd
import numpy as np

# 假设原始数据存储在df中
groups = []
for _, group in df.groupby('Customer'):
    groups.append(group)
    # 创建空行并添加到分组列表
    empty_row = pd.DataFrame([[np.nan]*len(df.columns)], columns=df.columns)
    groups.append(empty_row)

# 合并所有分组并移除最后一行多余的空行
result = pd.concat(groups, ignore_index=True).dropna(how='all').reset_index(drop=True)

# 打印格式化结果
print(result.to_string(index=False))

方法二:反向插入空行

先定位每个客户最后一行的索引,从后往前插入空行避免索引偏移:

import pandas as pd
import numpy as np

# 获取每个Customer最后一行的索引
last_indices = df.groupby('Customer').tail(1).index.tolist()

# 从后往前插入空行,防止索引偏移
for idx in reversed(last_indices):
    df.loc[idx + 0.5] = [np.nan]*len(df.columns)

# 排序索引并重置
df = df.sort_index().reset_index(drop=True)

# 打印格式化结果
print(df.to_string(index=False))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 16:56:03