Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
changing format to Int
#1
Hi everyone,

I am trying to change a format to int but I think it is having issues because the numbers have ,.

data['Imports_vfd'].astype(str).astype(int)
ValueError: invalid literal for int() with base 10: '7,255'

Anyone know how I can either remove the , form the column in the dataframe or convert to int with ,?

Thanks
Reply
#2
If the dash in string represents the thousands separator, just get rid of it first:

int(data['Imports_vfd'].replace(",", ""))
Reply
#3
Thanks, I tried that but it still won't let me convert to int.

data['Imports_vfd'].astype(str).astype(int(data['Imports_vfd'].replace(",", "")))
TypeError: cannot convert the series to <class 'int'>

Do you know what might be some of the common reasons for this?

Thanks
Reply
#4
Oh, sorry, now I see that data['Imports_vfd'] has Pandas Series data type. So you must first convert it to the string, then do the replace and then convert it to the integer:

# converting Pandas Series to string
str_value = data['Imports_vfd'].astype(str)

# removing the dash from the string
str_value = str_value.replace(",", "")

# converting the string without the dash into the integer
int_value = int(str_value)
Or on one row:

int_value = int(data['Imports_vfd'].astype(str).replace(",", ""))
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Issue in changing data format (2 bytes) into a 16 bit data. GiggsB 11 2,560 Jul-25-2022, 03:19 PM
Last Post: deanhystad
  Changing Number Format moby 4 4,997 May-24-2019, 11:04 PM
Last Post: snippsat
  changing { and } in str.format() Skaperen 10 4,917 May-16-2019, 05:07 AM
Last Post: Skaperen
  Date Format Changing Program Not Working pyth0nus3r 2 4,675 Jan-28-2017, 10:34 PM
Last Post: Ofnuts

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020