Python|熊猫 dataframe.round()
Python是一种用于进行数据分析的出色语言,主要是因为以数据为中心的Python包的奇妙生态系统。 Pandas就是其中之一,它使导入和分析数据变得更加容易。
Pandas dataframe.round()
函数用于将 DataFrame 舍入到可变的小数位数。此函数提供了按不同位置舍入不同列的灵活性。
Syntax:DataFrame.round(decimals=0, *args, **kwargs)
Parameters :
decimals : Number of decimal places to round each column to. If an int is given, round each column to the same number of places. Otherwise dict and Series round to variable numbers of places. Column names should be in the keys if decimals is a dict-like, or in the index if decimals is a Series. Any columns not included in decimals will be left as is. Elements of decimals which are not columns of the input will be ignored.
Returns : DataFrame object
示例 #1:使用round()
函数将数据框中的所有列四舍五入到小数点后 3 位
注意:我们需要用十进制值填充我们的数据框。让我们使用 numpy 随机函数来完成任务。
# importing pandas as pd
import pandas as pd
# importing numpy as np
import numpy as np
# setting the seed to re-create the dataframe
np.random.seed(25)
# Creating a 5 * 4 dataframe
df = pd.DataFrame(np.random.random([5, 4]), columns =["A", "B", "C", "D"])
# Print the dataframe
df
让我们使用dataframe.round()
函数将数据框中的所有十进制值四舍五入到小数点后 3 位。
df.round(3)
输出 :
示例 #2:使用round()
函数将数据框中的所有列四舍五入到不同的位置。
# importing pandas as pd
import pandas as pd
# importing numpy as np
import numpy as np
# setting the seed to re-create the dataframe
np.random.seed(25)
# Creating a 5 * 4 dataframe
df = pd.DataFrame(np.random.random([5, 4]), columns =["A", "B", "C", "D"])
# Print the dataframe
df
让我们将每一列四舍五入到不同的地方
# round off the columns in this manner
# "A" to 1 decimal place
# "B" to 2 decimal place
# "C" to 3 decimal place
# "D" to 4 decimal place
df.round({"A":1, "B":2, "C":3, "D":4})
输出 :