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

转置Pandas DataFrame的Col2后如何保留与Col1的列值对齐?

问题:转置Pandas DataFrame的Col2并保留对应Col1值

现有如下Pandas DataFrame数据:

import pandas as pd

data = {
    'Col1': [1]*30 + [2]*26,
    'Col2': ['33.5', 'W', 'A to B, OK', 'slinks down to hammer', 'T c V b Rell 10 (82b 6x1) DW: 84.14', '33.4', '•', 'A to B, no', 'Tosses it uo', '33.3', 2, 'A to B, 2 R', 'On a right way', 'slinks down to hammer', 'BAN: 185/4CRR: 5.60', 'T 69 (80b 6x4)', 'Mu 7 (17b)', 'Mark 6-0-29-1', 'George Dockrel', 'Bet 31', '33.2', 2, 'A to T, 2 R', 'slinks down to hammer', '33.1', 2, 'A to T, 2 r', 'angling away, cuts it',
            '33.5', 'W', 'A to B, OK', 'slinks down to hammer', 'T c V b Rell 10 (82b 6x1) DW: 84.14', '33.4', '•', 'A to B, no', 'Tosses it uo', '33.3', 2, 'A to B, 2 R', 'On a right way', 'slinks down to hammer', 'BAN: 185/4CRR: 5.60', 'T 69 (80b 6x4)', 'Mu 7 (17b)', 'Mark 6-0-29-1', 'George Dockrel', 'Bet 31', '33.2', 2, 'A to T, 2 R', 'slinks down to hammer', '33.1', 2, 'A to T, 2 r', 'angling away, cuts it']
}

df = pd.DataFrame(data)

需求是转置Col2的内容,同时保留对应的Col1值,使每个以浮点数/数字开头的分组对应相同的Col1值。原尝试代码无法保留Col1的对应值,代码如下:

#make a list
column_data = df['Col2'].tolist()

# Make overs float
column_data2 = []
for item in column_data:
    if isinstance(item, str) and item.replace('.', '', 1).isdigit():
        column_data2.append(float(item))
    else:
        column_data2.append(item)

df2 = pd.DataFrame(column_data2, columns=['Col2'])

# splits rows based on floats
rows = (df2.Col2.map(type)==float).cumsum()

df3 = df2.groupby(rows).agg(list)\
    .Col2.astype(str).str[1:-1]\
        .str.split(',', expand=True)\
            .add_prefix("col_")

df3

解决方案

原代码的核心问题是处理过程中丢失了Col1与分组的关联信息,我们需要在分组阶段就保留Col1的对应值,具体步骤如下:

  1. 标记分组起始点:严谨识别Col2中属于数字/浮点数的行,作为每个分组的起始,生成唯一分组ID
  2. 分组聚合:按分组ID聚合Col2的内容为列表,同时提取每个分组对应的Col1值(同一分组内Col1值一致,取第一个即可)
  3. 展开列表为列:将聚合后的Col2列表展开为多列,同时将Col1列插入到结果最前方,实现对齐

实现代码:

import pandas as pd

# 1. 定义函数判断是否为可转换为数字的项,生成分组ID
def is_numeric(item):
    if isinstance(item, (int, float)):
        return True
    if isinstance(item, str):
        try:
            float(item)
            return True
        except ValueError:
            return False
    return False

df['is_group_start'] = df['Col2'].apply(is_numeric)
df['group_id'] = df['is_group_start'].cumsum()

# 2. 分组聚合,保留Col1和Col2列表
grouped_df = df.groupby('group_id').agg(
    Col1=('Col1', 'first'),
    Col2_items=('Col2', list)
).reset_index(drop=True)

# 3. 将Col2列表展开为多列,合并Col1列
result_df = pd.DataFrame(grouped_df['Col2_items'].tolist()).add_prefix('col_')
result_df.insert(0, 'Col1', grouped_df['Col1'])

print(result_df)

关键说明:

  • 自定义is_numeric函数避免了原代码中字符串判断的漏洞,能正确识别整数、浮点数格式的字符串和数字类型
  • 直接基于原DataFrame分组,全程保留Col1与分组的关联,确保每个分组对应正确的Col1值
  • 最终结果中Col1列与转置后的Col2内容完全对齐,符合需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 09:27:43