pandas-22 數據去重處理
數據去重可以使用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
'''
