python更改数据框指定位置的数据,在python数据框中调换一列

I have the following:

Index ID speed _avg_val

245 1 10 30.5

246 1 2 25.1

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

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.

解决方案

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值