【问题标题】:How to group near-duplicate values in a pandas dataframe?如何在熊猫数据框中对近乎重复的值进行分组?
【发布时间】:2018-10-05 17:00:19
【问题描述】:

如果 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 的破解:

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

有没有更好的方法来实现这一点?

【问题讨论】:

    标签: python pandas pandas-groupby


    【解决方案1】:

    这是一个示例,您希望将项目分组到一位精度。您可以根据需要进行修改。您还可以修改此设置以对阈值超过 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
    

    【讨论】:

      猜你喜欢
      • 2017-12-13
      • 2020-06-22
      • 2021-11-02
      • 1970-01-01
      • 2022-01-25
      • 2017-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多