Home > database >  How to concatenate columns but with conditions?
How to concatenate columns but with conditions?

Time:04-05

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

CodePudding user response:

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
  • Related