python 去重
时间: 2023-11-15 10:00:01 浏览: 97
Python中有多种方法可以对列表和数据框进行去重操作。常用的方法包括:
1. 对列表去重:
- 使用循环查找的方式
- 使用set()函数
- 使用列表推导式
- 使用filter()函数
- 使用keys()方式
2. 对数据框去重:
- 使用unique()对单属性列去重
- 使用drop_duplicates()对单属性列去重
- 使用drop_duplicates()对多属性列去重
- 使用duplicated()对多属性列去重
其中,使用set()函数和列表推导式是最常用的方法之一。使用set()函数可以将列表转换为集合,从而去除重复元素。使用列表推导式可以通过遍历列表的方式,将不重复的元素添加到新列表中。
对于数据框的去重操作,可以使用unique()函数对单属性列进行去重,也可以使用drop_duplicates()函数对单属性列和多属性列进行去重。使用duplicated()函数可以返回一个布尔型的Series,表示每行是否是重复行。
相关问题
python去重排序
你可以使用Python中的set()函数来进行去重操作,然后使用sorted()函数对其进行排序。
以下是一个示例代码:
```python
lst = [1, 3, 2, 4, 2, 5, 1]
unique_sorted_lst = sorted(set(lst))
print(unique_sorted_lst)
```
输出结果为:[1, 2, 3, 4, 5]
python去重脚本
以下是一个Python的去重脚本的示例代码:
```python
import os
import glob
import filecmp
dir_path = r'D:\文件去重'
file_list = \[\]
count = 0
for i in glob.glob(dir_path + '/**/*', recursive=True):
if os.path.isfile(i):
file_list.append(i)
for x in file_list:
for y in file_list:
if x != y and os.path.exists(x) and os.path.exists(y):
if filecmp.cmp(x, y):
os.remove(y)
count += 1
print(f"运行结束,一共删除了{count}个重复文件")
```
这个脚本可以用于清除文件夹中的重复文件。它使用了os模块来与操作系统进行交互,glob模块用于查找文件目录和文件,并将搜索结果返回到一个列表中,filecmp模块用于比较文件的内容。脚本首先将文件添加到一个列表中,然后使用嵌套循环比较列表中的文件,如果发现重复的文件,则删除其中一个。最后,脚本会输出删除的重复文件的数量。
#### 引用[.reference_title]
- *1* [python 图片去重脚本](https://blog.csdn.net/HaoZiHuang/article/details/127756170)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* *3* [Python 实用脚本 实现文件重复去重](https://blog.csdn.net/Abieai/article/details/128836571)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文
相关推荐















