In [1]:
import pandas as pd
import numpy as np
from decimal import Decimal, ROUND_HALF_UP, ROUND_HALF_EVEN
import platform
In [2]:
print(platform.python_version())
print(pd.__version__)
print(np.__version__)
In [3]:
s_f = pd.Series([123.456, 654.123])
In [4]:
print(s_f)
In [5]:
print(s_f.round())
In [6]:
print(s_f.round().astype(int))
In [7]:
print(s_f.round(2))
In [8]:
print(s_f.round(-2))
In [9]:
s_i = pd.Series([123, 654])
In [10]:
print(s_i)
In [11]:
print(s_i.round())
In [12]:
print(s_i.round(2))
In [13]:
print(s_i.round(-2))
In [14]:
s_i_round = s_i.round(-2)
print(s_i_round)
In [15]:
print(s_i)
In [16]:
df = pd.DataFrame({'f': [123.456, 654.321], 'i': [123, 654], 's': ['abc', 'xyz']})
In [17]:
print(df)
In [18]:
print(df.dtypes)
In [19]:
print(df.round())
In [20]:
print(df.round(2))
In [21]:
print(df.round(-2))
In [22]:
print(df.round({'f': 2, 'i': -1}))
In [23]:
print(df.round({'i': -2}))
In [24]:
s = pd.Series([0.5, 1.5, 2.5, 3.5, 4.5])
print(s)
In [25]:
print(s.round())
In [26]:
s = pd.Series([5, 15, 25, 5.1, 15.1, 25.1])
print(s)
In [27]:
print(s.round(-1))
In [28]:
print('Python round')
print('0.005 => ', round(0.005, 2))
print('0.015 => ', round(0.015, 2))
print('0.025 => ', round(0.025, 2))
print('0.035 => ', round(0.035, 2))
print('0.045 => ', round(0.045, 2))
print('2.675 => ', round(2.675, 2))
In [29]:
print('NumPy np.around (np.round)')
print('0.005 => ', np.around(0.005, 2))
print('0.015 => ', np.around(0.015, 2))
print('0.025 => ', np.around(0.025, 2))
print('0.035 => ', np.around(0.035, 2))
print('0.045 => ', np.around(0.045, 2))
print('2.675 => ', np.around(2.675, 2))
In [30]:
s = pd.Series([0.005, 0.015, 0.025, 0.035, 0.045, 2.675])
print(s)
In [31]:
print(s.round(2))
In [32]:
print(Decimal(2.675))
In [33]:
print(Decimal('2.675'))
In [34]:
print(Decimal('2.675').quantize(Decimal('0.01'), rounding=ROUND_HALF_UP))
In [35]:
print(Decimal('2.675').quantize(Decimal('0.01'), rounding=ROUND_HALF_EVEN))
In [36]:
print(Decimal('0.5').quantize(Decimal('0'), rounding=ROUND_HALF_UP))
In [37]:
print(Decimal('0.5').quantize(Decimal('0'), rounding=ROUND_HALF_EVEN))
In [38]:
s = pd.Series([0.5, 1.5, 2.5, 3.5, 4.5])
In [39]:
print(s.map(lambda x: float(Decimal(str(x)).
quantize(Decimal('0'), rounding=ROUND_HALF_UP))))
In [40]:
s = pd.Series([0.005, 0.015, 0.025, 0.035, 0.045, 2.675])
In [41]:
print(s.map(lambda x: float(Decimal(str(x))
.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP))))
In [42]:
s = pd.Series([5, 15, 25, 5.1, 15.1, 25.1])
In [43]:
print(s.map(lambda x: int(Decimal(str(x))
.quantize(Decimal('1E1'), rounding=ROUND_HALF_UP))))
In [44]:
s = pd.Series([0.005, 0.015, 0.025, 0.035, 0.045, 2.675])
In [45]:
print(s.map(lambda x: float(Decimal(str(x))
.quantize(Decimal('0.01'), rounding=ROUND_HALF_EVEN))))