实现任务:pandas 查询DataFrame 某列元素中重复的数据项

duplicated官方说明参考

  • duplicated方法说明:

《实现任务:pandas 查询DataFrame 某列元素中重复的数据项》

  • 简洁代码实现:

import pandas as pd
from pandas import DataFrame

"""
实现任务:查询DataFrame 某列元素中重复的数据项
"""

if __name__ == '__main__':

    df = DataFrame({'key1': ['a', 'a', 'b', 'b', 'a', 'a', 'c', 'a'],
                    'key2': ['one', 'two', 'one', 'two', 'one2', 'one1', 'one', 'two',],
                    'data1': [1, 2, 3, 2, 5, 1, 3, 1],
                    'data2': [1, 2, 5, 5, 5, 1, 3, 1],
                    })
    print(df)
    # pandas  很简洁暴力的两行代码
    key_duplicated = df[df.key2.duplicated(False)]
    print("'key2' 列 中 重复元素所在数据如下:")
    print(key_duplicated[['key1', 'key2', 'data1']])

    # 可以考虑 按 'key2' 列元素进行排序
    sort_key_duplicated = key_duplicated.sort_values(by=['key2'])
    print(sort_key_duplicated)
  • 我自己写的呆萌方法(不需要看了):

import pandas as pd
from pandas import DataFrame

"""
实现任务:查询DataFrame 某列元素中重复的数据项
"""

if __name__ == '__main__':

    df = DataFrame({'key1': ['a', 'a', 'b', 'b', 'a', 'a', 'c', 'a'],
                    'key2': ['one', 'two', 'one', 'two', 'one2', 'one1', 'one', 'two',],
                    'data1': [1, 2, 3, 2, 5, 1, 3, 1],
                    'data2': [1, 2, 5, 5, 5, 1, 3, 1],
                    })
    # print(df)
    # 取出 key2 列的数据
    key = df.key2
    # print(key)
    print("key.duplicated(False)的返回为:")
    print(key.duplicated(False))

    print("==============")
    # 重复元素出现的索引位置
    indexs = []
    # 重复元素放到valueSet
    valueSet = set()
    dup = key.duplicated(False)
    for index, value in enumerate(dup):
        if value:
            indexs.append(index)
            valueSet.add(key[index])
    print("重复的值有:")
    print(valueSet)
    print("重复的值的索引为:")
    print(indexs)
    # 重复的元素个数
    num = 0
    # 重复的值按分组输出:
    for repeatVal in valueSet:
        flag = 0
        for index, value in enumerate(key):
            if repeatVal == value:
                if flag == 0:
                    print("-----find -----")
                    num += 1
                    flag = 1
                print(index, value)

    if num == 0:
        print("当前没有重复元素")
    else:
        print("本次查询重复的元素数量为 :%d" % num)

    原文作者:墨理学AI
    原文地址: https://blog.csdn.net/sinat_28442665/article/details/103704564
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞