Home > other >  How to combine 2 rows into one Pandas
How to combine 2 rows into one Pandas

Time:08-18

I have Series

    1 Lycan-Ogre Magi-Bloodseeker-Zeus-Tiny-WIN
    2 Tidehunter-Spectre-Warlock-Razor-Marci-LOSE
    3 Spectre-Enigma-Dazzle-Razor-Tiny-WIN
    4 Medusa-Hoodwink-Tusk-Beastmaster-Enchantress-LOSE

I want it to be like this

1 Lycan-Ogre Magi-Bloodseeker-Zeus-Tiny-WIN | Tidehunter-Spectre-Warlock-Razor-Marci-LOSE
2 Spectre-Enigma-Dazzle-Razor-Tiny-WIN | Medusa-Hoodwink-Tusk-Beastmaster-Enchantress-LOSE

CodePudding user response:

You can aggregate join by helper array created by integer division by 2:

print (df)
                                                 col
1          Lycan-Ogre Magi-Bloodseeker-Zeus-Tiny-WIN
2        Tidehunter-Spectre-Warlock-Razor-Marci-LOSE
3               Spectre-Enigma-Dazzle-Razor-Tiny-WIN
4  Medusa-Hoodwink-Tusk-Beastmaster-Enchantress-LOSE

df = (df.groupby(np.arange(len(df.index)) // 2)['col']
        .agg(' | '.join)
        .reset_index(drop=True)
        .to_frame())
print (df)
                                                 col
0  Lycan-Ogre Magi-Bloodseeker-Zeus-Tiny-WIN | Ti...
1  Spectre-Enigma-Dazzle-Razor-Tiny-WIN | Medusa-...
  • Related