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.
You can use df.round() method.
df.round(10)
df.round({'Col_1': 10, 'Col_3':10})
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With