Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Dataframe from another Dataframe

Tags:

python

pandas

I have a dataframe that looks like below

   Index  Batch    Name
    0        1      Jon
    1    
    2        2      Adam
    3         
    4        3      Voges
    5       
    6        4      Jon

I want to create another dataframe from this dataframe clubbing the batch numbers

Batch   Name/Batches
1        Jon(1,4)
2        Adam(2)
3        Voges(3)
4        Jon(1,4)

How can i do this, should i create a new list or ordereddict from the existing DF and then convert that to another DF or this can be done on the fly.

UPDATE: Edited with Spaces in between them

like image 850
Chris Avatar asked Dec 03 '25 10:12

Chris


1 Answers

In [33]: df['Name/Batches'] = \
             df['Name'] + '(' + \
             df.groupby('Name')['Batch'].transform(lambda x: x.astype(str).str.cat(sep=',')) \
             + ')'

In [34]: df
Out[34]:
   Batch   Name Name/Batches
0      1    Jon     Jon(1,4)
1      2   Adam      Adam(2)
2      3  Voges     Voges(3)
3      4    Jon     Jon(1,4)
like image 160
MaxU - stop WAR against UA Avatar answered Dec 05 '25 01:12

MaxU - stop WAR against UA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!