Home > database >  How to strip column and combine?
How to strip column and combine?

Time:10-25

df: 
   home_score  away_score
1         0.0         1.0
2         2.0         1.0
3         3.0         2.0
4         0.0         0.0
5         1.0         1.0

Expected result:

    score
--  -------
 0  0:1
 1  2:1
 2  2:1
 3  3:2

I am trying

df['home_score'] = df['home_score'].astype(str).str.replace('^.*(.\d)', '', regex=True)

to strip the score before combining columns but I am not getting anything..

Also, this code worked on regex101 How do I figure out this to work in python?

CodePudding user response:

Convert your columns to int first to remove decimal part then cast to string before join them:

cols = ['home_score', 'away_score']
df['score'] = df[cols].astype(int).astype(str).apply(':'.join, axis=1)
print(df)

# Output:
   home_score  away_score score
1         0.0         1.0   0:1
2         2.0         1.0   2:1
3         3.0         2.0   3:2
4         0.0         0.0   0:0
5         1.0         1.0   1:1
  • Related