0

My Current Dataframe looks like the below, I am having trouble changing the "fan of sport?" column to what i want it to look like.

import pandas as pd
df = pd.DataFrame([[1, "John","fb: Y, bb: N, cbb: N"], [2, "Joe","fb: Y, bb: N, cbb: Y"], [3, "Jess","fb: N, bb: Y, cbb: N"], [4,"James","fb: Y, bb: N, cbb: Y "]], columns=['id', 'name', "fan of sport"])

id |  name   |   fan of sport?      | 
1    John     fb: Y, bb: N, cbb: N 
2    Joe      fb: Y, bb: N, cbb: Y  
3    Jess     fb: N, bb: Y, cbb: N 
4    James    fb: Y, bb: N, cbb: Y 

Expected Dataframe

df = pd.DataFrame([[1, "John","|| fb || bb || cbb || | Y | N | N |"], [2, "Joe","|| fb || bb || cbb || | Y | N | Y |"], [3, "Jess","|| fb || bb || cbb || | N | Y | N |"], [4,"James","|| fb || bb || cbb || | Y | N | Y | "]], columns=['id', 'name', "fan of sport"])

id |  name   |   fan of sport?      | 
1    John     || fb || bb || cbb || | Y | N | N |

2    Joe      || fb || bb || cbb || | Y | N | Y |

3    Jess     || fb || bb || cbb || | N | Y | N | 

4    James    || fb || bb || cbb || | Y | N | Y | 

2 Answers2

0

It looks like you want to replace : with ||

For this, you can use the str.replace(':','||')

Example:

df['fan of sport?'] = df['fan of sport?'].str.replace(':','||')

The code basically replaces your current column with the new one. Just repeat for the other columns.

Pat Keenan
  • 22
  • 3
0

You can first remove the Y and N with replace to return fb, bb, cbbb, etc. Then, use re.findall to get all of the Ys and Ns.

df['fan of sport?'] = ('|| ' + df['fan of sport?'].replace(['Y', 'N', ',', ':'], 
                                                            ['||', '||', '', ''], regex=True)
                        + ' | ' + df['fan of sport?'].apply(lambda x: ' | '.join(re.findall('[Y|N]+', x))) + ' |')
df
Out[1]: 
   id   name                        fan of sport?
0   1   John  || fb || bb || cbb || | Y | N | N |
1   2    Joe  || fb || bb || cbb || | Y | N | Y |
2   3   Jess  || fb || bb || cbb || | N | Y | N |
3   4  James  || fb || bb || cbb || | Y | N | Y |
David Erickson
  • 16,433
  • 2
  • 19
  • 35