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

Pandas多列索引按列聚合:混合浮点与字符串列优化处理

解决方案:按列类型自动聚合带MultiIndex列的DataFrame

不用手动拆分字符串列和数值列再合并,我们可以直接通过分组聚合时根据列的数据类型自动选择聚合逻辑来实现需求,代码更简洁且可扩展:

import numpy as np
import pandas as pd

# 初始化原数据(和你的代码一致)
iterables_1 = [['bar', 'baz', 'foo'], ['one', 'two']]
iterables_2 = [['baz', 'foo', 'foz'], ['one', 'two']]
names = ['first', 'second']
columns_1 = pd.MultiIndex.from_product(iterables_1, names=names)
columns_2 = pd.MultiIndex.from_product(iterables_2, names=names)
index_1 = range(0, 5, 1)
index_2 = range(2, 9, 1)
data_1 = [[1] * 6] * 5
data_2 = [[2] * 6] * 7
df_1 = pd.DataFrame(data=data_1, columns=columns_1, index=index_1, dtype='float64')
df_2 = pd.DataFrame(data=data_2, columns=columns_2, index=index_2, dtype='float64')
df_4 = df_1.copy(deep=True)
df_4[('col', 'str')] = np.array(['A', 'B', 'C', 'D', 'E'])

# 步骤1:合并两个DataFrame
tmp = pd.concat([df_4, df_2], axis=1)

# 步骤2:构建聚合规则字典——根据列类型自动选择聚合方式
agg_dict = {}
# 获取所有唯一的MultiIndex列组
column_groups = tmp.columns.unique(level=('first', 'second'))
for group in column_groups:
    # 判断当前列组的数据类型
    col_dtype = tmp[group].dtype
    if np.issubdtype(col_dtype, np.number):
        # 数值型列:求和
        agg_dict[group] = 'sum'
    else:
        # 字符串/object型列:保留第一个非空值(要保留末值可换成'last')
        agg_dict[group] = 'first'

# 步骤3:执行分组聚合
df_5 = tmp.groupby(level=('first', 'second'), axis=1).agg(agg_dict)

# 查看结果
print(df_5)

输出结果(和你的预期完全一致):

first  bar     baz     foo     foz     col
second one two one two one two one two str
0      1.0 1.0 1.0 1.0 1.0 1.0 0.0 0.0 A
1      1.0 1.0 1.0 1.0 1.0 1.0 0.0 0.0 B
2      1.0 1.0 3.0 3.0 3.0 3.0 2.0 2.0 C
3      1.0 1.0 3.0 3.0 3.0 3.0 2.0 2.0 D
4      1.0 1.0 3.0 3.0 3.0 3.0 2.0 2.0 E
5      0.0 0.0 2.0 2.0 2.0 2.0 2.0 2.0 NaN
6      0.0 0.0 2.0 2.0 2.0 2.0 2.0 2.0 NaN
7      0.0 0.0 2.0 2.0 2.0 2.0 2.0 2.0 NaN
8      0.0 0.0 2.0 2.0 2.0 2.0 2.0 2.0 NaN

方案优势:

  • 无需手动拆分合并:自动识别列类型并应用对应聚合逻辑,避免繁琐的拆分-聚合-拼接流程
  • 可扩展性强:如果后续新增其他数据类型的列,只需在判断逻辑中添加对应规则即可
  • 逻辑清晰:通过字典明确指定每个列组的聚合方式,可读性更高

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 17:42:48