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!
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
Try this:
df['Category'] = df['Category'].apply(lambda x: 'A' + x if len(x) < 2 else x)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With