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

如何以Pythonic方式将DataFrame首列转为列名并完成转置?

Absolutely, there are a couple of clean, Pythonic ways to achieve this transformation in Pandas. Here are two straightforward approaches:

Method 1: Use set_index() + Transpose (T) + reset_index()

This method leverages Pandas' built-in index manipulation for a concise solution that works regardless of how many columns you have beyond the first one:

import pandas as pd

# Your original DataFrame
df = pd.DataFrame(data=[['a1',2,3],['b1',5,6],['c1',8,9]],columns=['A','B','C'])

# Transform to df2
df2 = df.set_index('A').T.reset_index(drop=True)

How it works:

  1. set_index('A') moves column A to become the row index of the DataFrame.
  2. .T transposes the DataFrame, swapping rows and columns—so your original row labels (a1, b1, c1) become the new column names, and original columns (B, C) become rows.
  3. reset_index(drop=True) removes the old row labels (B, C) and replaces them with the default integer index (0, 1).

Method 2: Directly create from transposed values

If you prefer a more explicit approach (or need to exclude specific columns), you can extract the values directly and transpose them:

df2 = pd.DataFrame(df.drop('A', axis=1).values.T, columns=df['A'].tolist())

How it works:

  1. df.drop('A', axis=1) removes the first column, leaving only the numeric data.
  2. .values.T transposes the underlying numpy array of numeric values.
  3. We create a new DataFrame using this transposed array, setting the column names to the values from the original A column.

Both methods will produce your desired df2:

a1  b1  c1
0   2   5   8
1   3   6   9

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:29:20