2017-05-29 56 views
-1

我有一个带有字符串列和浮点数列的pandas DataFrame我想用drop_duplicates删除重复项。有些重复的部分并不完全一样,因为在小数位低位有一些细微差别。如何删除重复精度较低的重复项?删除重复精度较低

例子:

import pandas as pd 
df = pd.DataFrame.from_dict({'text': ['aaa','aaa','aaa','bb'], 'result': [1.000001,1.000000,2,2]}) 
df 
    result text 
0 1.000001 aaa 
1 1.000000 aaa 
2 2.000000 aaa 
3 2.000000 bb 

我想获得

df_out = pd.DataFrame.from_dict({'text': ['aaa','aaa','bb'], 'result': [1.000001,2,2]}) 
df_out 
    result text 
0 1.000001 aaa 
1 2.000000 aaa 
2 2.000000 bb 
+0

Binning是一个针对此问题的过于复杂的解决方案,但我仍然会共享一个链接:https://chrisalbon.com/python/pandas_binning_data.html –

回答

1

可以为了圆你的DF使用功能round与给定精度。

DataFrame.round(小数= 0,*指定参数时,** kwargs)

回合数据帧到小数位的数目可变。

例如,您可以通过这个应用轮两位小数:

df = df.round(2) 

你也可以把它在特定列,例如:

df = df.round({'result': 2}) 

四舍五入后可以使用功能drop_duplictes

1

一轮他们

df.loc[df.round().drop_duplicates().index] 

    result text 
0 1.000001 aaa 
2 2.000000 aaa 
3 2.000000 bb 
0

使用numpy.trunc来获得您正在寻找的精度。使用pandasduplicated来查找要保留哪些。

df[~df.assign(result=np.trunc(df.result.values * 100)).duplicated()]