Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

Given below is a CSV file:

ID  A   B   C   R1  R2

-----------------------

1   A1  B1  C1  abc ghi

1   A1  B1  C2  def jkl

2   A2  B3  C1  mno stu

2   A2  B3  C2  pqr vwx

Need below output with the new column 'R':

ID  A   B  R

-------------------------

1   A1  B1 (abc, def) & (ghi, jkl)

2   A2  B3 (mno, pqr) & (stu, vwx)

Assume only C1, C2 values for column C

import pandas as pd

df = pd.read_csv(r'file.csv')

grouped_df = df.groupby(['ID', 'A', 'B'])

# Here how do we create a new and custom column?

1 Answer

0 votes
by (36.8k points)

You could use agg, ''.join and filter:

df.groupby(['ID','A','B'])

  .agg(lambda x: '('+', '.join(x)+')')

  .filter(like='R').agg('&'.join,1)

  .reset_index().rename(columns={0:'R'})

Details

df.groupby(['ID','A','B']).agg(lambda x: '('+', '.join(x)+')')

#                 C          R1          R2

#ID A  B                                   

#1  A1 B1  (C1, C2)  (abc, def)  (ghi, jkl)

#2  A2 B3  (C1, C2)  (mno, pqr)  (stu, vwx)

df.groupby(['ID','A','B']).agg(lambda x: '('+', '.join(x)+')').filter(like='R')

#                  R1          R2

#ID A  B                         

#1  A1 B1  (abc, def)  (ghi, jkl)

#2  A2 B3  (mno, pqr)  (stu, vwx)

df.groupby(['ID','A','B']).agg(lambda x: '('+', '.join(x)+')').filter(like='R').agg('&'.join,1).reset_index()

#   ID   A   B                      0

#0   1  A1  B1  (abc, def)&(ghi, jkl)

#1   2  A2  B3  (mno, pqr)&(stu, vwx)

df.groupby(['ID','A','B']).agg(lambda x: '('+', '.join(x)+')').filter(like='R').agg('&'.join,1).reset_index().rename(columns={0:'R'})

#   ID   A   B                      R

#0   1  A1  B1  (abc, def)&(ghi, jkl)

#1   2  A2  B3  (mno, pqr)&(stu, vwx)

Do check out Data Science with Python course which helps you understand from scratch 

Browse Categories

...