Python怎么统一列去重结果
时间: 2023-12-25 19:22:57 浏览: 23
如果您想要对多个列表进行去重,并且要将它们的结果合并为一个列表,可以使用 Python 的 set() 函数和 union() 方法。例如:
```python
list1 = [1, 2, 2, 3, 3, 4, 5, 5]
list2 = [2, 3, 4, 4, 5, 6, 7, 8]
list3 = [3, 4, 5, 6, 6, 7, 8, 9]
unique_list = list(set(list1).union(set(list2)).union(set(list3)))
print(unique_list)
```
输出结果为:[1, 2, 3, 4, 5, 6, 7, 8, 9]
在上面的代码中,首先将列表转换为 set 集合,这样会自动去重。然后使用 union() 方法将多个集合合并,并将合并后的结果转换回列表即可。
相关问题
Python怎么统计列去重结果
如果您想要对一个列表进行去重,并且统计每个元素出现的次数,可以使用 Python 的 Counter() 函数。例如:
```python
from collections import Counter
my_list = [1, 2, 2, 3, 3, 4, 5, 5]
count = Counter(my_list)
print(count)
```
输出结果为:Counter({2: 2, 3: 2, 5: 2, 1: 1, 4: 1})
在上面的代码中,首先使用 Counter() 函数对列表进行处理,然后将处理后的结果打印出来即可。Counter() 函数会返回一个字典,其中键为列表中的元素,值为该元素在列表中出现的次数。
python dataframe按列去重
可以使用pandas库中的drop_duplicates()函数来按列去重DataFrame。具体操作如下:
1. 选择需要去重的列,例如列名为‘col1’和‘col2’。
2. 使用drop_duplicates()函数,指定参数subset为需要去重的列名列表,例如subset=[‘col1’, ‘col2’]。
3. 将去重后的DataFrame赋值给原始DataFrame。
示例代码如下:
```python
import pandas as pd
# 创建DataFrame
df = pd.DataFrame({'col1': [1, 2, 3, 1], 'col2': ['a', 'b', 'c', 'a'], 'col3': [4, 5, 6, 7]})
# 按col1和col2列去重
df = df.drop_duplicates(subset=['col1', 'col2'])
print(df)
```
输出结果为:
```
col1 col2 col3
0 1 a 4
1 2 b 5
2 3 c 6
```