在Pandas中,我要转置数据并想命名列。

我当前的数据是:

    alpha   bravo    charlie
0   public  private  public
1   prodA   prodB    prodB
2   100     200      300


在对列进行转置和重命名之后,输出为:

df.transpose()
df.columns = ["category", "product", "price"]

    category    product price
alpha   public  prodA   100
bravo   private prodB   200
charlie public  prodB   300


如何获得预期的输出,例如:

company category product price
alpha   public   prodA   100
bravo   private  prodB   200
charlie public   prodB   300

最佳答案

只需先设置索引,然后转置数据框

df.index = pd.Index(['category','product','price'],name='company')
df.T

company category product price
alpha     public   prodA   100
bravo    private   prodB   200
charlie   public   prodB   300

10-07 15:09