如何在pandas数据框中分组近似重复的值?

7
如果DataFrame中存在重复的值,pandas已经提供了函数来替换或删除重复项。然而,在许多实验数据集中,可能会有“近似”重复项。如何使用例如它们的平均值替换这些接近重复的值呢?示例数据如下:
df = pd.DataFrame({'x': [1, 2,2.01, 3, 4,4.1,3.95, 5,], 
                   'y': [1, 2,2.2, 3, 4.1,4.4,4.01, 5.5]})

我尝试着拼凑一个东西去处理近似重复的内容,但是这个方法使用了for循环,看起来像是针对pandas的一种hack方法:

def cluster_near_values(df, colname_to_cluster, bin_size=0.1):

    used_x = [] # list of values already grouped
    group_index = 0
    for search_value in df[colname_to_cluster]:

        if search_value in used_x:
            # value is already in a group, skip to next
            continue

        g_ix = df[abs(df[colname_to_cluster]-search_value) < bin_size].index
        used_x.extend(df.loc[g_ix, colname_to_cluster])
        df.loc[g_ix, 'cluster_group'] = group_index
       group_index += 1

    return df.groupby('cluster_group').mean()

这个函数用于分组和求平均值:

print(cluster_near_values(df, 'x', 0.1))

                  x     y
cluster_group                
0.0            1.000000  1.00
1.0            2.005000  2.10
2.0            3.000000  3.00
3.0            4.016667  4.17
4.0            5.000000  5.50

有没有更好的方法来实现这个呢?
1个回答

3
这里有一个例子,你想将项目分组为一位有效数字。您可以根据需要进行修改。您还可以将其修改为使用阈值超过1的值进行分箱。
df.groupby(np.ceil(df['x'] * 10) // 10).mean()    
            x     y
x                  
1.0  1.000000  1.00
2.0  2.005000  2.10
3.0  3.000000  3.00
4.0  4.016667  4.17
5.0  5.000000  5.50

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接