Reputation: 3789
My dataframe is like below:
NameA 401016815
NameB
NameC 414969141
NameD 0403 612 699
How do I get dataframe to do a condition check [ first character is 4 and character length of number is 9 digits] and add a zero at start if the condition is met.
Condition check to see if character length in 12 digits but only contains 9 numbers, the space in between should be removed.
Upvotes: 0
Views: 222
Reputation: 30920
We can use Series.str.len
to check the length of the string. Series.startswith
to check the beginning of the string. Series.str.replace
to remove blanks. We use Series.mask
to replace or add characters in specific positions:
#df=df.reset_index() #if Names is the index
df['Number'].mask(df['Number'].str.len()>=12,df['Number'].str.replace(' ',''),inplace=True)
start=df['Number'].str.startswith('4').fillna(False)
df['Number'].mask(start,'0'+df['Number'],inplace=True)
print(df)
Output
Names Number
0 NameA 0401016815
1 NameB NaN
2 NameC 0414969141
3 NameD 0403612699
Upvotes: 1