【问题标题】:Generating values based on mean and std listed in a dataframe根据数据框中列出的均值和标准差生成值
【发布时间】:2022-11-19 00:23:58
【问题描述】:

我有这种格式的数据框:

import pandas as pd

df = pd.DataFrame({
    1: {'mean': 1.0, 'std': 0.8},
    2: {'mean': 0.5, 'std': 0.2},
    3: {'mean': 0.2, 'std': 0.1},
    4: {'mean': 0.1, 'std': 0.1},
    5: {'mean': 0.6, 'std': 0.2}
})

df
        1    2    3    4    5
mean  1.0  0.5  0.2  0.1  0.6
std   0.8  0.2  0.1  0.1  0.2

基于 mean 和 std 的这些值,我试图生成一个随机生成的正态分布数字的大数据框,它具有相同的列数但更多的行:

full_noise = []

for mean, std in enumerate(df):
    noise = np.random.normal(mean, std, [5, 1000]) 
    full_noise.append(noise)

因此,这个新数据框的每一列都将在上面的数据框中列出的mean和std上生成值。不过,我肯定做错了什么。

抱歉,我是 Python 的新手!我希望你能帮忙:(

【问题讨论】:

  • 你确定要这个mean, std in enumerate(df):吗?它会将mean设置为range(len(df))中的数字。
  • 不,我对这里的枚举完全不确定。只是不知道如何遍历 mean 和 std 的这些列,然后将值插入 np.random.normal 函数中。

标签: python pandas dataframe numpy


【解决方案1】:

要创建你想要的东西,我建议一次迭代数据框df一列(这样做首先转置数据框,然后使用iterrows)。

对于每一列,您可以使用列中的均值和标准差从正态分布中生成所需长度的 numpy 数组。

最后,您可以将 numpy 数组连接为数据框的列(axis=1)。

full_noise = []
for _, col in df.T.iterrows():
    noise = np.random.normal(loc=col["mean"], scale=col["std"], size=(1000,))
    full_noise.append(pd.Series(noise))

noise_df = pd.concat(full_noise, axis=1)

【讨论】:

    【解决方案2】:

    使用.apply制作full_noise。

    full_noise = df.apply(
        lambda col: np.random.normal(loc=col["mean"], scale=col["std"], size=(1_000,)),
    )
    
    print(full_noise)
    
                1         2         3         4         5
    0    0.900445  0.555275  0.206491  0.161578  0.491196
    1    1.555625  0.261742  0.196981 -0.068225  0.770397
    2    0.308983  0.256334  0.119617  0.157978  0.453351
    3    0.799080  0.255109  0.164719 -0.088953  0.462583
    4    1.263621  0.650327  0.217544  0.046004  0.893409
    ..        ...       ...       ...       ...       ...
    995  1.345332  0.827836  0.320708  0.113350  0.789898
    996  1.235461  0.464576  0.270596  0.049924  0.708799
    997  1.211508  0.751700  0.230916  0.176736  0.661312
    998  1.753942  0.941567  0.097372  0.177429  0.810710
    999  1.847943  0.240993 -0.006139  0.200517  0.523238
    
    [1000 rows x 5 columns]
    

    【讨论】:

      猜你喜欢
      • 2020-07-30
      • 1970-01-01
      • 2022-11-21
      • 2015-12-16
      • 2015-06-19
      • 1970-01-01
      • 2013-01-02
      • 2021-06-03
      • 1970-01-01
      相关资源
      最近更新 更多