You need to enable JavaScript to run this app. 如何将Pandas DataFrame转换为列名带索引前缀的一维序列
优惠活动
大模型
产品
解决方案
定价
更多

如何将Pandas DataFrame转换为列名带索引前缀的一维序列

实现方案

你可以通过Pandas的unstack+索引重命名实现需求,完整可运行代码如下:

import pandas as pd

# 构造你给出的示例DataFrame
df = pd.DataFrame(
    data={"A": [1, 2], "B": [3, 4]},
    index=["idx1", "idx2"]
)

# 转换逻辑
result = df.unstack().swaplevel()
# 重命名索引为「原列名_索引名」格式
result.index = result.index.map(lambda x: f"{x[0]}_{x[1]}")
# 如果需要转为一行的DataFrame结构,加一步转置即可
row_df = result.to_frame().T

运行后输出的result(Series结构)如下:

A_idx1    1
A_idx2    2
B_idx1    3
B_idx2    4
dtype: int64

row_df(一行的DataFrame结构)如下:

A_idx1  A_idx2  B_idx1  B_idx2
0       1       2       3       4

内容的提问来源于stack exchange,提问作者Guy Van-Dam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 21:36:00