Home > Software engineering >  How can I get my column to drop decimals unless it's necessary
How can I get my column to drop decimals unless it's necessary

Time:11-01

I have a column that is currently in dollars and my prof wants us to convert it so that it's showin inn 10,000's (for example 150000 will be 15, 30000 will be 3, 15000 will be 1.5). I was able to convert it but I don't know how to get it to only show the decimal if it's necessary (like the 15000 being 1.5). Does anyone know how I can get it to show whole numbers unless it's like 1.5?

medianIncome1 = (housing['medianIncome'].astype(float)/10000).astype(str)

If I use the astype(np.int64) it shows the whole number but if I don't it puts a bunch of decimals, if i use the round() i get the 0

CodePudding user response:

One way to do it is looping through the series and format them in this manner. There may be other efficient solutions out there.

for i in range(len(medianIncome1)):
  if medianIncome1[i].split('.')[1] == '0':
    medianIncome1[i]=round(float(medianIncome1[i]))

CodePudding user response:

Applying this option will work to show you what you want, but the underlying data will still be floats.

pd.set_option('display.float_format', lambda x: repr(int(x)) if x/1 == x//1 else repr(x))

CodePudding user response:

You can modify your existing code a bit to get the desired output

medianIncome1 = (housing['medianIncome'].astype(float)/10000).astype(str).str.rstrip('.0')
  • Related