简体   繁体   English

熊猫如何转置数据并添加列名

[英]Pandas how to transpose the data and add the column name

In Pandas I'm transposing the data and want to name the column. 在Pandas中,我要转置数据并想命名列。

My current data is: 我当前的数据是:

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

After transposing and renaming the columns, the output is: 在对列进行转置和重命名之后,输出为:

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

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

How can I have the expected output like: 如何获得预期的输出,例如:

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

Just setup the index first, then tanspose the dataframe 只需先设置索引,然后再放置数据框

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

First set the index name via df.index.set_names , then apply reset_index : 首先通过df.index.set_names设置索引名称,然后应用reset_index

df.index = df.index.set_names('company')
df.columns = ['category', 'product', 'price']
df = df.reset_index()

#    company category product price
# 0    alpha   public   prodA   100
# 1    bravo  private   prodB   200
# 2  charlie   public   prodB   300

You can us rename_axis and reset_index: 您可以使用rename_axis和reset_index:

(
    df.T
    .set_axis(["category", "product", "price"], axis=1, inplace=False)
    .rename_axis('company',axis=0)
    .reset_index()
)

Out[124]: 
   company category product price
0    alpha   public   prodA   100
1    bravo  private   prodB   200
2  charlie   public   prodB   300

If you would like to keep company as index: 如果要保留公司作为索引:

(
    df.T
    .set_axis(["category", "product", "price"], axis=1, inplace=False)
    .rename_axis('company',axis=0)
)
Out[125]: 
        category product price
company                       
alpha     public   prodA   100
bravo    private   prodB   200
charlie   public   prodB   300

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM