【问题标题】:How do I delete rows in a dataframe based on numpy where如何根据 numpy where 删除数据框中的行
【发布时间】: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 没有用;它根据条件生成值。

标签: python pandas numpy


【解决方案1】:

所以,你需要将数组转换为列表,然后使用df.drop

a = array([1,2,3,4])
a = a.tolist()
df = df.drop(df.index[[a]])

【讨论】:

  • 感谢您的回答。我之前尝试过,但出现以下错误:AttributeError: 'tuple' object has no attribute 'tolist'
  • drop() 可以像使用列表一样轻松获取数组,只需将其展平为一维数组
  • 显示数据样本或 where 函数以查看生成的类型,或者让我知道 Anderson 的想法是否成功
  • 我还添加了带有数据示例的示例代码
  • 所以这是有效的,但在两次迭代后将失败,因为索引将超出范围:a = np.array(a).tolist() print(a) df = df.drop(df.index[a])
【解决方案2】:

可能会让你感到困惑的是你有一个二维数组,而df.drop() 只接受一个一维数组或类似列表的对象。幸运的是,您可以使用索引或flatten() 对其进行排序。

如果您的数组被命名,例如,ind

df1=df.drop(ind.flatten(), axis=0)

df1=df.drop(ind[0], axis=0)

两者都应该可以,但是如果不查看示例数据就很难知道

【讨论】:

  • 谢谢!我试过你的代码,但它给了我错误。我还添加了带有数据示例的示例代码
猜你喜欢
  • 1970-01-01
  • 2019-09-15
  • 1970-01-01
  • 2016-11-01
  • 1970-01-01
  • 2018-05-28
  • 1970-01-01
  • 1970-01-01
  • 2022-07-23
相关资源
最近更新 更多