gpt4 book ai didi

python - 从宽到长 reshape Pandas 数据框

转载 作者:行者123 更新时间:2023-11-28 22:16:20 24 4
gpt4 key购买 nike

我正在尝试 reshape 下面的数据框:

        left_id                     right_id                    winner
482393 513d7a69fdc9f03587006808 513ceda3fdc9f035870023db left
653153 513d5fc2fdc9f03587003c2d 5185d41afdc9f03fd500137c right
1006476 5140c948fdc9f049260024b4 50f5e76afdc9f065f0007152 right

        id                              winner                                              
482393 513d7a69fdc9f03587006808 left
653153 513d5fc2fdc9f03587003c2d right
1006476 5140c948fdc9f049260024b4 right
482393 513ceda3fdc9f035870023db left
653153 5185d41afdc9f03fd500137c right
1006476 50f5e76afdc9f065f0007152 right

我试过 pd.melt(test_cat, id_vars=['left_id', 'right_id'], value_vars=['winner']) 但无法重现我的预期输出。我该怎么做?

示例数据:

pd.DataFrame({'left_id': {482393: '513d7a69fdc9f03587006808',
653153: '513d5fc2fdc9f03587003c2d',
1006476: '5140c948fdc9f049260024b4'},
'right_id': {482393: '513ceda3fdc9f035870023db',
653153: '5185d41afdc9f03fd500137c',
1006476: '50f5e76afdc9f065f0007152'},
'winner': {482393: 'left', 653153: 'right', 1006476: 'right'}}
)

最佳答案

melt 中交换参数:

df = pd.melt(test_cat, 
value_vars=['left_id', 'right_id'],
id_vars=['winner'],
value_name='id')
print (df)
winner variable id
0 left left_id 513d7a69fdc9f03587006808
1 right left_id 513d5fc2fdc9f03587003c2d
2 right left_id 5140c948fdc9f049260024b4
3 left right_id 513ceda3fdc9f035870023db
4 right right_id 5185d41afdc9f03fd500137c
5 right right_id 50f5e76afdc9f065f0007152

如果还需要索引值:

df = (pd.melt(test_cat.reset_index(), 
value_vars=['left_id', 'right_id'],
id_vars=['winner', 'index'])
.set_index('index')
.rename_axis(None))

print (df)

winner variable value
482393 left left_id 513d7a69fdc9f03587006808
653153 right left_id 513d5fc2fdc9f03587003c2d
1006476 right left_id 5140c948fdc9f049260024b4
482393 left right_id 513ceda3fdc9f035870023db
653153 right right_id 5185d41afdc9f03fd500137c
1006476 right right_id 50f5e76afdc9f065f0007152

或者使用set_indexstack :

df = test_cat.set_index('winner', append=True).stack().reset_index([1,2], name='id')
print (df)
winner level_2 id
482393 left left_id 513d7a69fdc9f03587006808
482393 left right_id 513ceda3fdc9f035870023db
653153 right left_id 513d5fc2fdc9f03587003c2d
653153 right right_id 5185d41afdc9f03fd500137c
1006476 right left_id 5140c948fdc9f049260024b4
1006476 right right_id 50f5e76afdc9f065f0007152

关于python - 从宽到长 reshape Pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52255752/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com