Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas string method to handle decimal places

Here is my little sample dataframe:

import pandas as pd
import numpy as np

size = 10000

arr1 = np.tile([1/5000,1/12000,1/7000], (size,1))

df = pd.DataFrame(arr1, columns = ['col1','col2','col3'])
df[['col1','col2','col3']] = df[['col1', 'col2', 'col3']].astype(str)

I want to use pandas string method to convert the 'col1', ' col2' and 'col3'to 10-decimal-place strings(so that '0.0002' becomes '0.0002000000', '8.333333333333333e-05' becomes '0.0000833333', and '0.00014285714285714287' becomes '0.0001428571'). What's the most pythonic way to achieve this?

EDIT1:

Added one more column to better represent my little problem

EDIT2: I want to mention that I know df.apply() and df.applymap() do exist and they can get the job done, but considering the performance as well, I am looking for a vectorizeed way to achieve this. Therefore I prefer pandas string methods. Of course, if no such string methods can achieve my goal, then I will gladly accept the top answer.

like image 367
mathguy Avatar asked Oct 27 '22 12:10

mathguy


1 Answers

You can use df.round() method.

  • If you want all column values to be rounded off to 10 decimal points:

df.round(10)

  • If you want only selected column values to be rounded off to 10 decimal points:

df.round({'Col_1': 10, 'Col_3':10})

  • If you want a series of column values to be rounded off to 10 decimal points:

decimals = pd.Series([10, 10, 10], index=['Col_1', 'Col_2', 'Col_3'])

df.round(decimals)

For more details, you can visit below example Link: https://pandas.pydata.org/pandasdocs/version/0.22/generated/pandas.DataFrame.round.html

like image 179
B-shan Avatar answered Nov 02 '22 10:11

B-shan