【发布时间】:2021-08-27 21:34:26
【问题描述】:
所以我有一个代码,我使用 numpy 将数据帧转换为数组,以计算数组中不同条目之间的汉明距离。
为了找到不需要的条目,我使用了一个 np.where 语句,它返回以下内容:
array([[1, 2, 3, 4]], dtype=int32)
有四个数字等于数据框中的行索引。我的问题是如何将这个数组转换为某些东西,以便我可以告诉数据框删除这些?
编辑: 这就是代码现在与示例数据的样子:
from sklearn.preprocessing import OrdinalEncoder
import pandas as pd
import numpy as np
data = [[1,1,1,1,1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1,1,1,1,2], [1,1,1,1,1,1,1,1,1,1,1,1,3]]
df = pd.DataFrame(data, columns=['csk_1', 'csk_2', 'csk_3', 'csk_4', 'csk_5', 'csk_6', 'csk_7', 'csk_8', 'csk_9', 'csk_10', 'csk_11', 'csk_12', 'csk_13'])
enc = OrdinalEncoder()
X = enc.fit_transform(df.to_numpy())
j = 0
totals = (len(X) - 1)
threshold = 1
while j < totals:
idx = len(X) - j - 1
row = X[idx]
prev_rows = X[0:idx]
dists = np.sum(row != prev_rows, axis=1)
a = np.where(dists <= threshold)
df = df.drop(a.flatten(), axis=0)
X = enc.fit_transform(df.to_numpy())
j = j + 1
print(df)
【问题讨论】:
-
到目前为止你尝试过什么?例如,来自the pandas drop() documentation: "labels (list-like): Index or column labels to drop" 如果您有要删除的索引,您是否尝试在 drop 方法中使用它们?
-
是的,我已经尝试过了,但没有成功。我对 Python 很陌生,所以我认为是我缺乏知识让我失败了。
-
查看此链接以了解如何创建minimal reproducible example,这将有助于我们了解如何在未来更好地帮助您。样本输入、预期输出和到目前为止您尝试过的代码(带有任何错误的完整追溯)让我们了解您卡在哪里
-
单参数
np.where,或者更确切地说np.nonzero可以为您提供可以在drop函数中使用的索引。pandas中使用的通常的 3 参数where没有用;它根据条件生成值。