Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to round to an integer AND remove the decimal point in an array in python

After rounding to an integer the result of operations between lists that produce an array is there a way to remove the decimal point? I am using python in Jupyter notebooks.

Should I use something other than 'np.round'?

'FoodSpent and 'Income' and are simply two lists of data that I created. The initial rounding attempt left the decimal point.

>>>PercentFood = np.around((FoodSpent / Income) * 100, 0)
>>>PercentFood

array([[ 10.,   7.,  11.,  10.,   6.,  10.,  10.,  12.,  11.,   9.,  11.,
         14.]

Thanks to advice given I ran the following, which rounded down to the integer without giving the decimal point.

>>> PercentFood = ((FoodSpent / Income) * 100)
>>> PercentFood.astype(int)

array([[ 9,  6, 11,  9,  6,  9, 10, 11, 10,  9, 11, 13]])



like image 869
chenderson Avatar asked Sep 03 '25 09:09

chenderson


2 Answers

The answer suggested by the OP performs a floor operation (rounding "down" to the nearest integer). For more typical rounding use hpaulj's suggestion:

import numpy as np

foo = [1.1, 1.9, 3.4, 3.5]
bar = np.rint(foo).astype(int)
print(bar)

Which results in:

[1, 2, 3, 4]
like image 104
Fifteen12 Avatar answered Sep 05 '25 00:09

Fifteen12


I'm not sure how exactly your code works with this much context, but you can put this after rounding to get rid of the decimal.

PercentFood = [round(x) for x in PercentFood]

like image 31
GlerG Avatar answered Sep 04 '25 23:09

GlerG