5

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.

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.