【问题标题】:Set the value of 10 random non-zero values per row to zero将每行 10 个随机非零值的值设置为零
【发布时间】:2018-07-24 09:43:21
【问题描述】:

我有一个约 1,000 行和约 10,000 列的非常稀疏的 Pandas DataFrame。大多数行仅包含 20-100 个非零值。我现在想在每行中选择任意 10 个随机非零值并将它们的值设置为 0。

这是我的第一次(非常不友好的)尝试:

for i in range(df.shape[0]):
    row = df.iloc[i]
    nonZeros = np.where(row > 0)[0]
    rand = np.random.choice(nonZeros, 10)
    for j in rand:
        df.iloc[i, j] = 0

【问题讨论】:

  • 到目前为止你尝试了什么?请向我们展示您的代码。
  • @running.t 在我的问题中添加了代码
  • 使用数据帧的apply 方法将函数应用于数据帧的每一行(axis=1)。

标签: python pandas


【解决方案1】:

这样的?

def setrandom(x):
    counter=10
    while counter>0:
        randindex = np.random.randint(1,10000)
        if x[randindex] !=0:
            x[randindex] = 0
            counter -=1        
    return x

df = df.apply(setrandom, axis=1)

这并不是真正的最佳方式,尤其是因为您的数据框是稀疏的!

【讨论】:

    【解决方案2】:

    修改后的答案

    您可以使用以下代码:

    df_with_more_zeros = df.apply(lambda x: x.replace(to_replace=x[x!=0].sample(10), value=0), axis=1)
    

    也许不是最快的方式,但对 Pandas 更友好一点

    【讨论】:

    • 我不知道为什么,但这非常慢。我的原始方法需要大约 6 秒,并且在至少 60 秒左右没有完成后,我已经停止了您的方法。
    • 是的,实际上我犯了一个错误。看看我编辑的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-04
    • 2014-03-26
    相关资源
    最近更新 更多