如何基于内层索引拼接Pandas多级索引DataFrame数值并删除对应索引层
实现方法
核心逻辑
先把数值列统一转为字符串格式,再按外层索引key分组,对所有列执行\n拼接的聚合操作即可,无需额外手动删除索引层,分组聚合后内层nm索引会自动被消去。
完整代码示例
第一步:构造示例数据(如果你已有对应DataFrame可跳过这一步)
import pandas as pd # 构造和你结构一致的多级索引DataFrame arrays = [ ['bar', 'bar', 'baz', 'baz'], ['one', 'two', 'one', 'two'] ] index = pd.MultiIndex.from_arrays(arrays, names=('key', 'nm')) df = pd.DataFrame( [[-0.42, 0.56, 0.27, -1.08], [-0.67, 0.11, -1.47, 0.52], [0.40, 0.57, -1.71, -1.03], [-0.37, -1.15, -1.34, 0.84]], index=index, columns=['c0', 'c1', 'c2', 'c3'] )
第二步:执行转换和聚合操作
# 先转字符串,再按外层key分组,每列用\n拼接 result_df = df.astype(str).groupby(level="key").agg("\n".join)
输出结果验证
打印result_df即可得到你需要的格式:
c0 c1 c2 c3 key bar -0.42\n-0.67 0.56\n0.11 0.27\n-1.47 -1.08\n0.52 baz 0.40\n-0.37 0.57\n-1.15 -1.71\n-1.34 -1.03\n0.84
内容的提问来源于stack exchange,提问作者vvv
相关产品推荐
相关产品推荐

