Home > other >  How to remove the commas from string with no spaces for int conversion
How to remove the commas from string with no spaces for int conversion

Time:10-29

enter image description here

I'm trying to remove the commas from this data set so they can be converted to int and be summed up all but I can't seem to find any way to do it without introducing spaces to the number values.

enter image description here

 parse = g.readlines()[8:]
 for x in parse:
    val0 = x.strip(',')
    val = val0.split(" ")
    i15.append(val[1])

this is my current code trying to remove the commas.

CodePudding user response:

parse = g.readlines()[8:]
for x in parse:
    val0 = x.replace(',' , '')
    val = val0.split(" ")
    i15.append(val[1])

Try this

CodePudding user response:

Try this, it works like charm for me

with open("dataset.txt") as f:
    contents=f.read()
    contents_without_comma=contents.replace(",","")
    print(contents_without_comma)

CodePudding user response:

Assumption: Panda Data frame has been used

You can use below code to solve your problem

df1['columnname'] = df1['columnname'].str.replace(',', '')

Hope this solve your problem

CodePudding user response:

I think in first You need to correctly parse data before you will append it to your array where you want to have it as a String or Int or any other type.

Below my solution for your problem:

lines = g.readlines()
for line in lines:
  x = line[2:].strip('').replace('  ', ' ').replace(',' , '').split(' ') // extract numbers from string assuming that first two characters are always characters that identify the data in a row
  for elem in x:
    if elem.isnumeric(): // append only elements that have numeric values
      i.append(int(elem))
  • Related