Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add another string to complete existing strings

Tags:

python

pandas

I have some data that look like

Category
A
C
E
J
AA
AB
AE
AK
AO
F
L
O
AW
AQ

The correct data should have two letters, such as AA, AB, and AK. However, some entries only have the second alphabet.

The final result would be:

Category
AA
AC
AE
AJ
AA
AB
AE
AK
AO
AF
AL
AO
AW
AQ

I know how we can add a string "A" to all entries in this column. However, is it possible to only add "A" to entries with one letter?

Thanks a lot for the help!

like image 300
IceAloe Avatar asked May 08 '26 16:05

IceAloe


2 Answers

Use Series.str.pad:

df['Category'] = df['Category'].str.pad(2, side='left', fillchar='A')

[out]

   Category
0        AA
1        AC
2        AE
3        AJ
4        AA
5        AB
6        AE
7        AK
8        AO
9        AF
10       AL
11       AO
12       AW
13       AQ
like image 193
Chris Adams Avatar answered May 11 '26 05:05

Chris Adams


Try this:

df['Category'] = df['Category'].apply(lambda x: 'A' + x if len(x) < 2 else x)

like image 30
hacker315 Avatar answered May 11 '26 05:05

hacker315



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!