0

I have a pandas dataframe with two columns, first one entitled "Letters" has two letters (ex. AB) and the other one entitled "Numbers" has numbers (from 1 to 9999). Now I want to merge them so that the first row with "Letters" = XY and "Numbers" = 4 would become XY0004, basically ensuring that both cells are merged but the number cell has additional 0 zeros added. Row 2 with ZW and 333 would become ZW0333. Row 3 with AB and 1234 would become AB1234. How can I do this well?

Huebschi
  • 59
  • 6

2 Answers2

1

Use the pandas astype to convert int to str and use zfill to add leading zero's:

# Example dataframe
df = pd.DataFrame({'Letters':['AB', 'XY', 'ZW'],
                   'Numbers': [1234, 4, 333]})

print(df)
  Letters  Numbers
0      AB     1234
1      XY        4
2      ZW      333

df['Merged'] = df['Letters'] + df['Numbers'].astype(str).str.zfill(4)

print(df)
  Letters  Numbers  Merged
0      AB     1234  AB1234
1      XY        4  XY0004
2      ZW      333  ZW0333

Edit after OP commented that he has floats as numeric values.
Like ChrisA suggested, use the following:

df['Merged'] = df['Letters'] + df['Numbers'].astype(int).astype(str).str.zfill(4)

print(df)
  Letters  Numbers  Merged
0      AB   1234.0  AB1234
1      XY      4.0  XY0004
2      ZW    333.0  ZW0333
Erfan
  • 40,971
  • 8
  • 66
  • 78
  • Thanks for the full answer. It works, the only issue I have is that I get this AB1234.0 How do I get rid of the .0? – Huebschi Apr 08 '19 at 18:42
  • @Huebschi maybe need `df['Letters'] + df['Numbers'].astype(int).astype(str).str.zfill(4)` to get rid of decimal ? – Chris Adams Apr 08 '19 at 18:56
  • What ChrisA, says. Apparently you have `float` type numbers instead of `integers`. See edit for solution @Huebschi – Erfan Apr 08 '19 at 18:59
  • Yes, that worked, thank you very much. Sorry for my ignorance :) – Huebschi Apr 08 '19 at 19:13
0

Try:

df['New Col'] = df.apply(lambda row: row['Letters'] + str(row['Numbers']).zfill(4), axis=1)

This will mutate your DataFrame to include a new column.

Luke Ning
  • 147
  • 6