【问题标题】:Finding Columns with less than 3 duplications of every categorical value in a data frame python在数据框python中查找每个分类值重复少于3个的列
【发布时间】:2021-02-25 14:42:46
【问题描述】:

基本上,我试图找出每个类的重复次数少于 3 个的分类列。例如,在随附的屏幕截图中,我有一个名为 Name, 'Type 1' 的列,如果这些列中的每个类别,我希望在我的输出中返回这些列名列(比如 Bulbasaur,Nidoino)存在

以下是我尝试过的代码,但我没有找到解决方案。

有人可以帮忙吗?

labels = [str(Training_data[object_cols].unique()[i]) for i in range(Training_data[object_cols].nunique())]
values = [Training_data[object_cols].value_counts()[i] for i in range(Training_data[object_cols].nunique())]
labels
values
Target_dis = pd.DataFrame((labels, values))
Target_dis = Target_dis.T
Target_dis.columns = ['Labels', 'Counts']
Target_dis = Target_dis.sort_values('Counts', ascending=False)
Target_dis

【问题讨论】:

    标签: python dataframe for-loop duplicates


    【解决方案1】:

    我不确定您到底想要什么,以及为什么要进行标签编码。所以 -- 我在输出下面添加了一些代码,对于每一列,最常见的值出现了多少次。

    import pandas as pd
    
    df = pd.DataFrame({
        'Name': ['Bulbasaur', 'Bulbasaur', 'Nidorino', 'Nidoking', 'Clefairy', 'Clefable', 
                 'Vulpix', 'Ninetales', 'Jigglypuff'],
        'Type 1': ['Grass', 'Grass', 'Grass', 'Grass', 'Fire', 'Fire', 'Fire', 'Fire', 'Fire'],
        'Type 2': ['Poison', 'Poison', 'Poison', 'Poison', '', '', 'Flying', 'Dragon', 'Flying'],
        'Total': [318, 405, 525, 625, 309, 405, 534, 634, 634],
        'HP': [45, 60, 80, 80, 39, 58, 78, 78, 78],
        'Attack': [49, 62, 82, 100, 52, 64, 84, 130, 104],
    })
    
    for col in df:
        max_count = df[col].value_counts().max()
        print(f"Values in column '{col}' are repeated at most {max_count} times.")
    
    Values in column 'Name' are repeated at most 2 times.
    Values in column 'Type 1' are repeated at most 5 times.
    Values in column 'Type 2' are repeated at most 4 times.
    Values in column 'Total' are repeated at most 2 times.
    Values in column 'HP' are repeated at most 3 times.
    Values in column 'Attack' are repeated at most 1 times.
    

    【讨论】:

      【解决方案2】:

      您可以在列上使用value_counts 方法:

      Target_dis['Name'].value_counts()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-08
        • 1970-01-01
        • 2022-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多