数据帧内的 pandas 转座 [英] Pandas transposition inside dataframe

查看:162
本文介绍了数据帧内的 pandas 转座的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在有这个数据:

 动物年龄计数
狗1 49
2 134
3 147
4 154
猫1 189
2 254
3 259
4 261

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

 动物年龄1年龄2年龄3年龄4 
狗49 134 147 154
猫....................

我尝试过df.T和df.transpose(),但都是返回原始列。

解决方案

您可以使用 pd.pivot

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

在[26]中:结果
输出[26]:
年龄1 2 3 4
动物
猫189 254 259 261
狗49 134 147 154

在[27]中:result.columns = ['age {:d}'。result.columns中col的格式(col)]

在[28]中:result
Out [28]:
age1 age2 age3 age4
animal
cats 189 254 259 261
dogs 49 134 147 154
/ pre>

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:

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.

解决方案

You could use 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

这篇关于数据帧内的 pandas 转座的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆