Home > OS >  Pandas how to find length of an integer in column value
Pandas how to find length of an integer in column value

Time:03-09

I have a DataFrame, you can have it by run following code:

import numpy as np
import pandas as pd
from io import StringIO
df = """
  contract      EndDate     
  A00118        12345678     
  A00118        123456   
  A00118        12345    
 
"""

df = pd.read_csv(StringIO(df.strip()), sep='\s ')
df

The output is:

contract    EndDate
0   A00118  12345678
1   A00118  123456
2   A00118  12345 

How to apply this logic to it: if the EndDate has only 6 digits ,then add 00 to then end of it,the output should be:

contract    EndDate
0   A00118  12345678
1   A00118  12345600
2   A00118  12345000 

Any friend can help?

CodePudding user response:

You could use str.ljust to pad from the right side:

length = df['EndDate'].astype(str)
df['EndDate'] = length.str.ljust(length.str.len().max(), '0')

If you want EndDate to be int dtype, you can of course use astype:

df['EndDate'] = length.str.ljust(length.str.len().max(), '0').astype(int)

Output:

  contract   EndDate
0   A00118  12345678
1   A00118  12345600
2   A00118  12345000
  • Related