Combine two number columns but exclude zero

Viewed 32

I have the following dataframe from a database download that I cleaned up a bit. Unfortunately some of the single numbers split into a second column (row 9) from a single one. I'm trying to merge the two columns but exclude the zero values.

               city  crashes  crashes_1  total_crashes
1          ABERDEEN      710          0            710
2      ACHERS LODGE        1          0              1
3              ACME        1          0              1
4           ADVANCE       55          0             55
5             AFTON        2          0              2
6           AHOSKIE      393          0            393
7      AKERS CENTER        1          0              1
8          ALAMANCE       50          0             50
9         ALBEMARLE        1         58             59

So for row 9 I want to end with:

9         ALBEMARLE        1         58            158

I tried a few snippets but nothing seems to work:

df['total_crashes'] = df['crashes'].astype(str).str.zfill(0) + df['crashes_1'].astype(str).str.zfill(0)

df['total_crashes'] = df['total_crashes'].astype(str).replace('\0', '', regex=True)

df['total_crashes'] = df['total_crashes'].apply(lambda x: ''.join(x[x!=0]))

df['total_crashes'] = df['total_crashes'].str.cat(df['total_crashes'], x[x!=0])

df['total_crashes'] = df.drop[0].sum(axis=1)

Thanks for any help.

1 Answers

You can use where condition:

df['total_crashes'] = df['crashes'].astype(str) + df['crashes_1'].astype(str).where(df['crashes_1'] != 0, "")
Related