Pandas Dataframe如何在不舍入的情况下截断浮点小数点?

时间:2019-06-26 20:40:33

标签: python pandas dataframe truncate

我在彼此靠近的两个数据框中具有经度和纬度。如果我运行完全相似的检查,例如

test_similar = test1_latlon.loc[~test1_latlon['cr'].isin(test2_latlon['cr'])]

我失败很多,因为很多数字在小数点后第五位。我想在第三个小数点后截断。我见过人们格式,因此它会被截断,但我想更改实际值。使用round()会使数据四舍五入,并且出现了更多错误,是否有办法仅在小数点后3位下降?

3 个答案:

答案 0 :(得分:3)

按照建议的here,您可以执行以下操作:

x = 1.123456
float( '%.3f'%(x) )

如果您想要更多的小数位,只需将3更改为所需的任何数字即可。

答案 1 :(得分:1)

import math

value1 = 1.1236
value2 = 1.1266

value1 = math.trunc(1000 * value1) / 1000;
value2 = math.trunc(1000 * value2) / 1000;

#value1 output
1.123

#value2 output
1.126

答案 2 :(得分:1)

您可能要使用numpy.trunc:

import numpy as np
import pandas as pd

df = pd.DataFrame([[1.2366, 1.2310], [1, 1]])
df1 = np.trunc(1000 * df) / 1000
print(df1, type(df1))
#        0      1
# 0  1.236  1.231
# 1  1.000  1.000 <class 'pandas.core.frame.DataFrame'>

请注意,df1仍然是DataFrame而不是numpy.array