在python数据框中调换一列 [英] Transposing one column in python dataframe

查看:828
本文介绍了在python数据框中调换一列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下内容:

Index  ID     speed  _avg_val
245    1      10      30.5
246    1      2       25.1

我想转置列ID,然后具有以下内容:

I want to transpose the column ID and then have the following:

ID (Index)    speed   _avg_val   speed_y   _avg_val_y
1             10      30.5       2         25.1

我尝试使用这种方法以最简单的索引将python pandas中的一列转换成可能的,但是无法让这个列与多个列一起工作。

I tried to use this method Transposing one column in python pandas with the simplest index possible but could not get this to work with multiple columns.

推荐答案

我想您可以先删除列索引,然后添加列 ID 索引 ,然后按照在列中对第二级MultiIndex进行排序 sort_index

I think you can first remove column Index, then add column ID to index, unstack and sort second level of MultiIndex in columns by sort_index:

print (df)
   Index  ID  speed  _avg_val
0    245   1     10      30.5
1    246   1      2      25.1


df = df.drop('Index', axis=1)
       .set_index('ID', append=True)
       .unstack(0)
       .sort_index(axis=1, level=1)

#remove MultiIndex from columns
df.columns = ['_'.join((col[0], str(col[1]))) for col in df.columns]

print (df)
    speed_0  _avg_val_0  speed_1  _avg_val_1
ID                                          
1        10        30.5        2        25.1

如果 ID 列中有更多值,则需要使用 cumcount

If there is more values in ID column, need use cumcount:

print (df)
   Index  ID  speed  _avg_val
0    245   1     10      30.5
1    246   1      2      25.1
2    245   2      5      37.5
3    246   2     28      28.1
4    246   2     27      23.0

df = df.drop('Index', axis=1)
df['g'] = df.groupby('ID').cumcount()
df = df.set_index(['ID', 'g']).unstack(fill_value=0).sort_index(axis=1, level=1)
df.columns = ['_'.join((col[0], str(col[1]))) for col in df.columns]

print (df)
    speed_0  _avg_val_0  speed_1  _avg_val_1  speed_2  _avg_val_2
ID                                                               
1        10        30.5        2        25.1        0         0.0
2         5        37.5       28        28.1       27        23.0

这篇关于在python数据框中调换一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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