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

如何对DataFrame按ID分组并转置Apple至Mango区间的行数据

解决方案:Pandas 按ID提取特定行转置合并到首行

嘿,我懂你现在卡在哪了——知道要groupby和转置,但就是没法精准只对Apple到Mango那几行操作,对吧?别慌,用Pandas一步步就能搞定,我给你捋清楚:

1. 先构造示例数据(和你给出的结构一致)

import pandas as pd
import numpy as np

# 模拟你的原始DataFrame
data = {
    'ID': [1,1,1,1,1,1,1,1,1,2],
    'Name': ['Fruit','xxx','yyy','Apple','aaa','bbb','Mango','abc','lmn','Fruit1'],
    'Price': [10.5,10.5,8.5,4.2,4.1,0.1,2.1,1,np.nan,7.6]
}
df = pd.DataFrame(data)

2. 定义分组处理函数

核心思路是对每个ID组单独处理:先保留首行,再定位Apple和Mango的位置,提取中间行转置后合并到首行:

def process_id_group(group):
    # 1. 保留当前ID的首行数据
    first_row = group.iloc[0:1].copy()
    
    # 2. 检查当前组是否存在Apple和Mango(避免报错)
    has_apple = not group[group['Name'] == 'Apple'].empty
    has_mango = not group[group['Name'] == 'Mango'].empty
    
    if has_apple and has_mango:
        # 3. 获取Apple和Mango的索引位置
        apple_idx = group[group['Name'] == 'Apple'].index[0]
        mango_idx = group[group['Name'] == 'Mango'].index[0]
        
        # 4. 提取Apple到Mango之间的所有行(包括这两个行)
        target_rows = group.loc[apple_idx:mango_idx, ['Name', 'Price']]
        
        # 5. 把提取的行转置为「列名=Name,值=Price」的字典
        target_cols = target_rows.set_index('Name')['Price'].to_dict()
        
        # 6. 将转置后的列添加到首行
        for col_name, col_value in target_cols.items():
            first_row[col_name] = col_value
    
    return first_row

3. 分组应用函数并输出结果

# 按ID分组,应用处理函数,然后拼接结果
final_result = df.groupby('ID', group_keys=False).apply(process_id_group).reset_index(drop=True)

print(final_result)

输出结果完全符合你的需求:

ID    Name  Price  Apple  aaa  bbb  Mango
0   1   Fruit   10.5    4.2  4.1  0.1    2.1
1   2  Fruit1    7.6    NaN  NaN  NaN    NaN

关键细节说明

  • 自动忽略了xxx、abc这类无关行,因为我们只提取了Apple到Mango的范围
  • 加了存在性检查,如果某个ID没有Apple或Mango,不会报错,只会保留首行数据
  • 每个ID的首行内容(比如ID1的Fruit、ID2的Fruit1)都完整保留

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:51:47