Home > Software engineering >  Get a portion of numbers from a pandas column with dtype int
Get a portion of numbers from a pandas column with dtype int

Time:02-10

How do I get the first 8 digits from a column with 15 digits?

data = [['tom', 355552107972100], ['nick', 356557107972103], ['juli', 455552107972100]]

df = pd.DataFrame(data, columns = ['Name', 'Code']) 
    Name    Code
0   tom     355552107972100
1   nick    356557107972103
2   juli    455552107972100

I want to create a new column with the first 8 digits from the code column

CodePudding user response:

Convert values to strings and use indexing:

df['Code'] =  df['Code'].astype(str).str[:8].astype(int)

Or:

df['Code'] =  df['Code'].map(lambda x: int(str(x)[:8]))

CodePudding user response:

@jezrael comment is correct, but you can also divide each number by 10000000, and convert to int:

df['Code'] = (df['Code']/10000000).astype('int')
  • Related