Issue
how do i split the values in the column COD into 3 columns with different length? in particular as you can see below i need one number on the first column, 2 numbers on the second and 3 on the third. Any idea?
COD CODA CODB CODC
140022 1 40 022
140031 1 40 031
140032 1 40 032
140033 1 40 033
140034 1 40 034
140035 1 40 035
140036 1 40 036
Thanks!
Solution
As you want to keep leading zeros, you have to handle everything as strings.
You can use str.extract
:
df[['CODA', 'CODB', 'CODC']] = df['COD'].astype(str).str.extract('(.)(..)(...)')
If for some reason you're not sure that the input has 6 digits (this would fill preferentially from the right):
df[['CODA', 'CODB', 'CODC']] = (df['COD'].astype(str).str.zfill(6)
.str.extract('(.)(..)(...)$')
)
For filling from the left:
df[['CODA', 'CODB', 'CODC']] = (df['COD'].astype(str).str.ljust(6, '0')
.str.extract('^(.)(..)(...)')
)
output:
COD CODA CODB CODC
0 140022 1 40 022
1 140031 1 40 031
2 140032 1 40 032
3 140033 1 40 033
4 140034 1 40 034
5 140035 1 40 035
6 140036 1 40 036
Answered By - mozway
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.