numpy去除矩阵中重复的行
时间: 2023-05-26 08:02:23 浏览: 60
可以使用numpy.unique函数来去除矩阵中重复的行,设置参数axis=0即可按行去重。具体代码如下:
```python
import numpy as np
# 定义矩阵
mat = np.array([[1, 2, 3],
[4, 5, 6],
[1, 2, 3],
[7, 8, 9],
[4, 5, 6]])
# 对矩阵按行去重
unique_mat = np.unique(mat, axis=0)
print("原矩阵:\n", mat)
print("去重后矩阵:\n", unique_mat)
```
运行结果如下:
```
原矩阵:
[[1 2 3]
[4 5 6]
[1 2 3]
[7 8 9]
[4 5 6]]
去重后矩阵:
[[1 2 3]
[4 5 6]
[7 8 9]]
```
相关问题
共现矩阵实现代码python
以下是一个简单的 Python 代码示例,用于创建共现矩阵:
```python
import numpy as np
# 语料库
corpus = ["I like apples and oranges",
"I eat apples every day",
"Oranges are juicy and delicious"]
# 构建单词列表
words = []
for sentence in corpus:
words.extend(sentence.split())
# 去除重复的单词,构建单词表
words = list(set(words))
word_index = {w: i for i, w in enumerate(words)}
# 初始化共现矩阵
num_words = len(words)
co_matrix = np.zeros((num_words, num_words))
# 构建共现矩阵
for sentence in corpus:
sentence_words = sentence.split()
for i in range(len(sentence_words)):
for j in range(i+1, len(sentence_words)):
index_i = word_index[sentence_words[i]]
index_j = word_index[sentence_words[j]]
co_matrix[index_i][index_j] += 1
co_matrix[index_j][index_i] += 1
# 打印共现矩阵
print(co_matrix)
```
在这个示例中,我们首先定义了一个语料库作为输入。然后,我们从所有句子中提取所有单词,并构建一个单词表。接下来,我们初始化共现矩阵,并在每个句子中计算单词之间的共现关系,并更新共现矩阵。最后,我们打印共现矩阵。
用python求矩阵每列大于0的最小值
可以使用NumPy库来实现这个功能。具体步骤如下:
1. 导入NumPy库
```python
import numpy as np
```
2. 定义矩阵
假设我们要求解的矩阵为`mat`,可以用以下代码定义:
```python
mat = np.array([[1, -2, 3], [4, 5, -6], [-7, 8, 9]])
```
3. 使用`np.where`函数找到每列大于0的元素的索引
```python
indices = np.where(mat > 0)[1]
```
这里`np.where`函数返回的是一个元组,第一个元素是行索引的数组,第二个元素是列索引的数组。因为我们只需要列索引,所以使用索引`1`来获取。
4. 使用`np.unique`函数获取不重复的列索引
```python
unique_indices = np.unique(indices)
```
这里`np.unique`函数可以帮助我们去除重复的列索引。
5. 使用`np.min`函数找到每列大于0的最小值
```python
result = np.min(mat[:, unique_indices], axis=0)
```
这里`mat[:, unique_indices]`表示取出矩阵`mat`中所有行,但只取出列索引在`unique_indices`中的列。然后使用`np.min`函数找到每列的最小值,最后使用`axis=0`参数来指定按列进行计算。
完整代码如下:
```python
import numpy as np
mat = np.array([[1, -2, 3], [4, 5, -6], [-7, 8, 9]])
indices = np.where(mat > 0)[1]
unique_indices = np.unique(indices)
result = np.min(mat[:, unique_indices], axis=0)
print(result)
```
输出结果为:
```
[1 8]
```
表示第一列和第三列都大于0,它们的最小值分别为1和8。