pandas中的資料去重處理
阿新 • • 發佈:2018-12-29
資料去重可以使用duplicated()和drop_duplicates()兩個方法。
DataFrame.duplicated(subset = None,keep =‘first’ )返回boolean Series表示重複行
引數:
subset:列標籤或標籤序列,可選
僅考慮用於標識重複項的某些列,預設情況下使用所有列
keep:{‘first’,‘last’,False},預設’first’
- first:標記重複,True除了第一次出現。
- last:標記重複,True除了最後一次出現。
- 錯誤:將所有重複項標記為True。
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
df = pd.read_csv('./demo_duplicate.csv')
print(df)
print(df['Seqno'].unique()) # [0. 1.]
# 使用duplicated 檢視 重複值
# 引數 keep 可以標記重複值 {'first','last',False}
print(df['Seqno'].duplicated())
'''
0 False
1 True
2 True
3 True
4 False
Name: Seqno, dtype: bool
'''
# 刪除 series 重複資料
print(df['Seqno'].drop_duplicates())
'''
0 0.0
4 1.0
Name: Seqno, dtype: float64
'''
# 刪除 dataframe 重複資料
print(df.drop_duplicates(['Seqno'])) # 按照 Seqno 來 去重
'''
Price Seqno Symbol time
0 1623.0 0.0 APPL 1473411962
4 1649.0 1.0 APPL 1473411963
'''
# drop_dujplicates() 第二個引數 keep 包含的值 有: first、last、False
print(df.drop_duplicates(['Seqno'], keep='last')) # 儲存最後一個
'''
Price Seqno Symbol time
3 1623.0 0.0 APPL 1473411963
4 1649.0 1.0 APPL 1473411963
'''