Pandas之drop_duplicates:去除重复项

前言

本文,我们讲述Pandas如何去除重复项的操作,我们选择一个评价数据集来演示如何删除特定列上的重复项,如何删除重复项并保留最后一次出现,以及drop_duplicates的默认用法

方法

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

返回值

这个drop_duplicate方法是对DataFrame格式的数据,去除特定列下面的重复行。

返回删除重复行的 DataFrame。 考虑某些列是可选的。索引(包括时间索引)将被忽略。

参数

返回DataFrame格式的数据。

  • subset : column label or sequence of labels, optional
    用来指定特定的列,默认所有列
  • keep : {‘first’, ‘last’, False}, default ‘first’
    删除重复项并保留第一次出现的项
  • inplace : boolean, default False
    是直接在原来数据上修改还是保留一个副本

实验

构建包含拉面评级的数据集

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
brand style rating
0 Yum Yum cup 4.0
1 Yum Yum cup 4.0
2 Indomie cup 3.5
3 Indomie pack 15.0
4 Indomie pack 5.0

默认情况下,它会根据所有列删除重复的行

df.drop_duplicates()

brand style rating
0 Yum Yum cup 4.0
2 Indomie cup 3.5
3 Indomie pack 15.0
4 Indomie pack 5.0

要删除特定列上的重复项,请使用subset

df.drop_duplicates(subset=['brand'])

brand style rating
0 Yum Yum cup 4.0
2 Indomie cup 3.5

要删除重复项并保留最后一次出现,请使用 keep

df.drop_duplicates(subset=['brand', 'style'], keep='last')

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

1

在数据结构中,要检索或查找一个数组中的数,可以使用线性查找或二分查找两种方法。 1. 线性查找:从数组的第一个元素开始逐个比较,直到找到目标元素或者遍历整个数组。时间复杂度为O(n),其中n为数组的长度。 下面是一个用C语言实现线性查找的例子: ```c #include <stdio.h> int linear_search(int arr[], int n, int target) { for (int i = 0; i < n; i++) { if (arr[i] == target) { return i; } } return -1; } int main() { int arr[] = {1, 3, 5, 7, 9, 11}; int n = sizeof(arr) / sizeof(arr[0]); int target = 7; int index = linear_search(arr, n, target); if (index == -1) { printf("The target element is not found in the array.\n"); } else { printf("The target element is found at index %d.\n", index); } return 0; } ``` 2. 二分查找:对于已排序的数组,可以使用二分查找算法来快速查找目标元素。时间复杂度为O(log n),其中n为数组的长度。 下面是一个用C语言实现二分查找的例子: ```c #include <stdio.h> int binary_search(int arr[], int n, int target) { int left = 0, right = n - 1; while (left <= right) { int mid = (left + right) / 2; if (arr[mid] == target) { return mid; } else if (arr[mid] < target) { left = mid + 1; } else { right = mid - 1; } } return -1; } int main() { int arr[] = {1, 3, 5, 7, 9, 11}; int n = sizeof(arr) / sizeof(arr[0]); int target = 7; int index = binary_search(arr, n, target); if (index == -1) { printf("The target element is not found in the array.\n"); } else { printf("The target element is found at index %d.\n", index); } return 0; } ``` 这里我们使用了一个while循环来实现二分查找,每次将查找范围缩小一半。当查找到目标元素时,返回其下标;否则,继续缩小查找范围。
评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Roaring Kitty

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

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

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

打赏作者

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

抵扣说明:

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

余额充值