pandas 笔记:Drop_duplicates

1 方法介绍

去除Pandas中的重复列

DataFrame.drop_duplicates(
    subset=None, 
    *,
    keep='first', 
    inplace=False, 
    ignore_index=False)

2 参数说明

subset

只考虑subset中提到的这些列是不是重复的,其他列重复也不用考虑

默认:所有列

keep

决定重复的那些行怎么处置

有三个选项:

  • 'first':除了第一次出现的重复行,其他的都去掉
  • 'last':除了最后一次出现的重复行,其他的都去掉
  • False:所有重复行都去掉
inplace是否替换原DataFrame
ignore_index如果为True,重新排index

3 举例

3.0 原始数据

df = pd.DataFrame({
    'brand': ['Yum Yum', 'Yum Yum', 'Indomie', 'Indomie', 'Indomie'],
    'style': ['cup', 'cup', 'cup', 'pack', 'pack'],
    'rating': [4, 4, 3.5, 15, 5]
})
df

 3.1  基本用法

df.drop_duplicates()

 3.2  subset

df.drop_duplicates(subset='style')

3.3  keep

df.drop_duplicates(keep='last')

df.drop_duplicates(keep=False)

4 同时保留第一条和最后一条duplicate记录

由于keep只能在first和last中选,所以如果想保留第一和最后一条,那么就需要额外的操作:

还是之前的数据:

df = pd.DataFrame({
    'brand': ['Yum Yum', 'Yum Yum', 'Indomie', 'Indomie', 'Indomie'],
    'style': ['cup', 'cup', 'cup', 'pack', 'pack'],
    'rating': [4, 4, 3.5, 15, 5]
})
df

keep为first和last各进行一次

df1=df.drop_duplicates('brand','first')
df1
'''
	brand	style	rating
0	Yum Yum	cup	    4.0
2	Indomie	cup	    3.5
'''

df2=df.drop_duplicates('brand','last')
df2
'''
	brand	style	rating
1	Yum Yum	cup	    4.0
4	Indomie	pack	5.0
'''

concat+重新排序

df_d=pd.concat([df1,df2])
df_d
'''
	brand	style	rating
0	Yum Yum	cup	    4.0
2	Indomie	cup	    3.5
1	Yum Yum	cup	    4.0
4	Indomie	pack	5.0
'''

df_d=df_d.sort_index()
df_d
'''

brand	style	rating
0	Yum Yum	cup	4.0
1	Yum Yum	cup	4.0
2	Indomie	cup	3.5
4	Indomie	pack	5.0
'''

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

UQI-LIUWJ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值