在上一篇中,我介紹了collections中的counter模塊,並簡單介紹了其使用。這一篇中,我將通過一個例子展示其如何在pandas中快速查找某列中的重複數據。
>>> import pandas as pd
>>> import numpy as np
>>> df = pd.read_excel('D:/2.xlsx')
>>> df
姓名 電話
0 lb 1232
1 lc 3222
2 ac 1222
3 ah 1433
4 eg 1222
5 fs 1232
6 ee 4333
7 rr 1111
8 afa 1222
9 fa 3232
10 fg 3232
我將通過代碼展示如何快速查找電話中重複的電話號碼。
>>> from collections import Counter
>>> phones = Counter(df['電話'])
# 通過調用most_common()方法,能夠獲取到
# 排序以後的結果
>>> phones_sort = phones.most_common()
# 以下列表解析的結果是遍歷結果並
# 排除掉val <= 1的結果,並返回key
>>> [ item[0] for item in phones_sort if item[1] > 1]
[1222, 1232, 3232]
# phones_sort的結果
>>> phones_sort
[(1222, 3), (1232, 2), (3232, 2), (3222, 1), (1433, 1), (4333, 1), (1111, 1)]
昨天通過200個以上的電話號碼實驗,速度也是非常快的,非常適合辦公人事使用哦。有興趣歡迎關注python小工具,一起學習python和pandas.