Ask Your Question
3

How can the precision be varied across different columns in pandas?

asked 2023-01-14 11:00:00 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-12-28 15:00:00 +0000

woof gravatar image

One way to vary the precision of different columns in a pandas DataFrame is to use the "round" method with the "decimals" parameter, which allows you to specify the number of decimal places to round to. Here's an example:

import pandas as pd

# create a sample DataFrame with two columns
df = pd.DataFrame({'A': [0.123456789, 1.23456789, 12.3456789],
                   'B': [0.987654321, 9.87654321, 98.7654321]})

# round the 'A' column to 2 decimal places and the 'B' column to 4 decimal places
df_rounded = df.round({'A': 2, 'B': 4})

print(df_rounded)

This will output:

       A       B
0   0.12  0.9877
1   1.23  9.8765
2  12.35 98.7654

Note that you can also pass a single integer value to the "round" method to round all columns to the same number of decimal places. For example, df.round(2) would round all columns to 2 decimal places.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-01-14 11:00:00 +0000

Seen: 11 times

Last updated: Dec 28 '22