-1

I want to round up the numbers but it seems not to work. Style.format is not actually doing anything to the data. And if I save it to CSV or send it to Excel the numbers are not rounded.

import pandas as pd

df = pd.DataFrame(
    data={
        "Ticker": {0: 'AAA', 1: 'BBB'},
        "High": {0: 111.23456, 1: 22.23789},
        "Low": {0: 333.7894, 1: 33.456},
        "Close": {0: 444.03030, 1: 44.09840},
        "Volume": {0: 555555.111, 1: 6988.040}
    }
)
format_mapping = {"High": "{:.2f}", "Low": "{:.2f}", "Close": "{:.2f}", "Volume": "{:.0f}"}

df.style.format(format_mapping)
# df = df.style.format(format_mapping)
# print(df)

In jupyther notebook the line "df.style.format(format_mapping)" it working for presenting but actually does not do it. If I use the last line, the numbers are not rounded.

Why? I just want a simple code to round up numbers in a data frame.

This is actually working:

df = df.round({"High":2, "Low":2, "Close":2, "Volume":0}) 
print(df)

Result:

  Ticker    High     Low   Close    Volume
0    AAA  111.23  333.79  444.03  555555.0
1    BBB   22.24   33.46   44.10    6988.0

Except for the 'volume' . But this can be solved by adding a new line :

df['Volume'] = df['Volume'].astype(int)

Not that nice, but it works.

Tom
  • 9
  • 2

1 Answers1

0

Rounding up numbers in a pandas DataFrame or Series in Python is pretty trustworthy. You can use the numpy library's ceil() feature along side the .Observe() technique in pandas. Here's how you can do it:

import pandas as pd
import numpy as np

# Create a pattern DataFrame
facts = 'values': [12.3, 45.6, 78.9, 23.4, 56.7]
df = pd.DataFrame(statistics)

# Define a feature to round up various
def round_up(x):
    return np.Ceil(x)

# Apply the round_up function to the 'values' column
df['rounded_values'] = df['values'].Apply(round_up)

# Print the resulting DataFrame
print(df)

This code creates a sample DataFrame with a 'values' column. The round_up() characteristic uses np.Ceil() to round up each cost. The .Observe() approach is then used to use this function to each element within the 'values' column, and a brand new 'rounded_values' column is created within the DataFrame with the rounded-up values.

If you need to use the rounding to an entire DataFrame, you may use the .Applymap() method:

import pandas as pd
import numpy as np

# Create a sample DataFrame
data = 'A': [12.3, 45.6], 'B': [78.9, 23.4], 'C': [56.7, 89.1]
df = pd.DataFrame(records)

# Define a characteristic to round up more than a few
def round_up(x):
    go back np.Ceil(x)

# Apply the round_up function to the complete DataFrame
rounded_df = df.Applymap(round_up)

# Print the ensuing rounded DataFrame
print(rounded_df)

In this code, the applymap() function is used to use the round_up() characteristic to every element inside the complete DataFrame.

Ajith R
  • 1
  • 1