【问题标题】:Numpy array with different standard deviation and mean per row具有不同标准差和每行平均值的 Numpy 数组
【发布时间】:2020-02-05 21:36:49
【问题描述】:

我有一个包含两列的 pandas 数据框。它们代表平均值和标准差。

如何执行矢量化采样?我想每行采样 1 个观察值。

import numpy as np
import pandas as pd

rng = np.random.RandomState(0)

#n_points = 4_000_000
n_points = 10
d_dimensions = 2

X = rng.random_sample((n_points, d_dimensions))

df = pd.DataFrame(X)
display(df.head())

df['raondomized'] = df.apply(lambda x: np.random.normal(x[0], x[1], 1), axis = 1)
df.head()

记录数增加时很慢。

Numpy array with different standard deviation per row

np.random.seed(444)
arr = np.random.normal(loc=0., scale=[1., 2., 3.], size=(1000, 3)).T

print(arr.mean(axis=1))
# [-0.06678394 -0.12606733 -0.04992722]
print(arr.std(axis=1))
# [0.99080274 2.03563299 3.01426507]

展示如何以相等的方式执行矢量化采样 - 如何更改它以支持不同的方式,就像我使用 apply 的幼稚版本一样,但更快?

答:

np.random.normal(df[0], df[1], 1)

仅返回单个标量值,即使指定了多个均值/标准差。

【问题讨论】:

    标签: python pandas numpy vectorization sampling


    【解决方案1】:
    df['raondomized'] = np.random.normal(df[0], df[1])
    

    重要的是不要指定元素的数量。

    【讨论】:

      【解决方案2】:

      怎么样

      np.random.normal(df[0], df[1], len(df))
      

      您还可以指定每个规格的运行次数(比如 1000 次),

      np.random.normal(df[0], df[1], (1000, len(df)))
      

      【讨论】:

        猜你喜欢
        • 2019-09-11
        • 1970-01-01
        • 1970-01-01
        • 2016-03-11
        • 2021-03-22
        • 2020-04-15
        • 1970-01-01
        • 2018-06-17
        • 1970-01-01
        相关资源
        最近更新 更多