pandas 数据帧内的熊猫换位

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24116600/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 22:08:42  来源:igfitidea点击:

Pandas transposition inside dataframe

pythonpython-2.7pandasdataframetranspose

提问by Aidis

I have this datasate now:

我现在有这个数据:

animal   age             count
dogs     1               49
         2              134
         3              147
         4              154
cats     1              189
         2              254
         3              259
         4              261

I would like to convert age column to 4 age columns for each age:

我想将年龄列转换为每个年龄的 4 个年龄列:

animal   age1 age2 age3 age4 
dogs      49   134  147  154  
cats     ....................   

I have tried df.T and df.transpose() but both of them return my original column.

我尝试过 df.T 和 df.transpose() 但它们都返回了我的原始列。

回答by unutbu

You could use pd.pivot:

你可以使用pd.pivot

In [25]: result = df.pivot(index='animal', columns='age', values='count')

In [26]: result
Out[26]: 
age       1    2    3    4
animal                    
cats    189  254  259  261
dogs     49  134  147  154

In [27]: result.columns = ['age{:d}'.format(col) for col in result.columns]

In [28]: result
Out[28]: 
        age1  age2  age3  age4
animal                        
cats     189   254   259   261
dogs      49   134   147   154