Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to concatenate columns but with conditions?

I am trying to concatenate 2 columns (B and A) but the fact is that I want to add a 0 always unless the column A has a number of 3 digits (Where I do not want to add any 0). On the other hand, when the column A has a number of One digit I want to add another extra 0 (00).

Here is my expected result:

A   B
1   7
12  10
1   10
124 10
133 3
12  4

C
7001
10012
10001
10124
3133
4012

Thanks in advance

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It seems you simply want:

df['B']*1000+df['A']

output:

0     7001
1    10012
2    10001
3    10124
4     3133
5     4012
dtype: int64

in case you have strings: zfill

df2 = pd.DataFrame({'A': ['1', '12', '1', '124', '133', '12'],
                    'B': ['7', '10', '10', '10', '3', '4']})

df2['B']+df2['A'].str.zfill(3)

output:

0     7001
1    10012
2    10001
3    10124
4     3133
5     4012
dtype: object
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading