Pandas Dataframe 如何在不四舍五入的情况下切断浮点数?
Pandas Dataframe How to cut off float decimal points without rounding?
我在两个靠得很近的数据框中有经度和纬度。如果我 运行 进行精确的相似性检查,例如
test_similar = test1_latlon.loc[~test1_latlon['cr'].isin(test2_latlon['cr'])]
我遇到了很多失败,因为很多数字都在小数点后 5 位。我想 t运行cate 在小数点后第三位。我见过有人格式化所以它显示为 t运行cated,但我想更改实际值。使用 round()
对数据进行四舍五入,我得到了更多错误,那么有没有办法只保留小数点后 3 位?
按照建议here你可以这样做:
x = 1.123456
float( '%.3f'%(x) )
如果您想要更多小数位,只需将 3 更改为您需要的任何数字即可。
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
您可能想使用 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
我在两个靠得很近的数据框中有经度和纬度。如果我 运行 进行精确的相似性检查,例如
test_similar = test1_latlon.loc[~test1_latlon['cr'].isin(test2_latlon['cr'])]
我遇到了很多失败,因为很多数字都在小数点后 5 位。我想 t运行cate 在小数点后第三位。我见过有人格式化所以它显示为 t运行cated,但我想更改实际值。使用 round()
对数据进行四舍五入,我得到了更多错误,那么有没有办法只保留小数点后 3 位?
按照建议here你可以这样做:
x = 1.123456
float( '%.3f'%(x) )
如果您想要更多小数位,只需将 3 更改为您需要的任何数字即可。
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
您可能想使用 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