如何以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:
set_index('A')moves columnAto become the row index of the DataFrame..Ttransposes 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.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:
df.drop('A', axis=1)removes the first column, leaving only the numeric data..values.Ttransposes the underlying numpy array of numeric values.- We create a new DataFrame using this transposed array, setting the column names to the values from the original
Acolumn.
Both methods will produce your desired df2:
a1 b1 c1 0 2 5 8 1 3 6 9
内容的提问来源于stack exchange,提问作者gabboshow
相关产品推荐
相关产品推荐

