【问题标题】:Student - np.random.choice: How to isolate and tally hit frequency within a np.random.choice range学生 - np.random.choice:如何在 np.random.choice 范围内隔离和统计命中频率
【发布时间】:2016-08-01 19:36:36
【问题描述】:

目前正在学习 Python,对 Numpy 和 Panda 还很陌生

我已经拼凑了一个带有范围的随机生成器。它使用 Numpy,我无法隔离每个单独的结果来计算随机范围内的迭代次数。

目标:计算“随机 >= 1000”的迭代次数,然后将 1 加到与迭代计数相关的相应单元格中。非常基本的例子:

#Random generator begins... these are first four random generations
Randomiteration0 = 175994 (Random >= 1000)
Randomiteration1 = 1199 (Random >= 1000)
Randomiteration2 = 873399 (Random >= 1000)
Randomiteration3 = 322 (Random < 1000)

#used to +1 to the fourth row of column A in CSV
finalIterationTally = 4

#total times random < 1000 throughout entire session. Placed in cell B1
hits = 1
#Rinse and repeat to custom set generations quantity...

(然后在电子表格中的逻辑是 +1 到 A4。如果迭代计数是 7,那么 +1 到 A7,等等。所以基本上,我正在测量距离和频率之间的距离每个“命中”)

我当前的代码包含一个 CSV 导出部分。我不再需要导出每个单独的随机结果。我只需要导出每次命中之间每次迭代距离的频率。这就是我难过的地方。

干杯

import pandas as pd
import numpy as np

#set random generation quantity
generations=int(input("How many generations?\n###:"))

#random range and generator
choices = range(1, 100000)
samples = np.random.choice(choices, size=generations)

#create new column in excel
my_break = 1000000
if generations > my_break:
    n_empty = my_break - generations % my_break
    samples = np.append(samples, [np.nan] * n_empty).reshape((-1, my_break)).T

#export results to CSV
(pd.DataFrame(samples)
 .to_csv('eval_test.csv', index=False, header=False))

#left uncommented if wanting to test 10 generations or so
print (samples)

【问题讨论】:

    标签: python pandas numpy random range


    【解决方案1】:

    我相信您混淆了迭代和世代。听起来您想要 N 代数进行 4 次迭代,但是您的底部代码在任何地方都没有表达“4”。如果您将所有变量拉到脚本的顶部,它可以帮助您更好地组织。 Panda 非常适合解析复杂的 csv,但对于这种情况,您并不需要它。你可能甚至不需要 numpy.

    import numpy as np
    
    THRESHOLD = 1000
    CHOICES = 10000
    ITERATIONS = 4
    GENERATIONS = 100
    
    choices = range(1, CHOICES)
    
    output = np.zeros(ITERATIONS+1)
    
    for _ in range(GENERATIONS):
      samples = np.random.choice(choices, size=ITERATIONS)
      count = sum([1 for x in samples if x > THRESHOLD])
      output[count] += 1
    
    output = map(str, map(int, output.tolist()))
    
    with open('eval_test.csv', 'w') as f:
      f.write(",".join(output)+'\n')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-05
      • 1970-01-01
      • 2021-12-07
      • 2016-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多