我想对数字进行四舍五入,但似乎行不通。 Style.format 实际上并没有对数据做任何事情。如果我将其保存到 CSV 或发送到 Excel,数字不会四舍五入。
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)
在jupyther笔记本中,“df.style.format(format_mapping)”行用于呈现,但实际上并没有这样做。如果我使用最后一行,数字不会四舍五入。
为什么?我只想要一个简单的代码来对数据框中的数字进行四舍五入。
这确实有效:
df = df.round({"High":2, "Low":2, "Close":2, "Volume":0})
print(df)
结果:
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
除了“音量”。但这可以通过添加新行来解决:
df['Volume'] = df['Volume'].astype(int)
不是那么好,但它有效。
在 Python 中对 pandas DataFrame 或 Series 中的数字进行四舍五入是非常值得信赖的。您可以使用
numpy
库的 ceil()
功能以及 pandas 中的 .Observe()
技术。具体方法如下:
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)
此代码创建一个带有“值”列的示例 DataFrame。
round_up()
特性使用 np.Ceil()
对每个成本进行四舍五入。然后使用 .Observe()
方法将此函数用于“values”列中的每个元素,并在 DataFrame 中创建一个具有舍入值的全新“rounded_values”列。
如果需要对整个 DataFrame 使用舍入,可以使用
.Applymap()
方法:
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)
在此代码中,
applymap()
函数用于将round_up()
特征用于完整DataFrame内的每个元素。