繁体   English   中英

使用 Pandas 在特定范围内生成与其他列值相关的随机数

[英]Generate random numbers in a specific range that correlates to other column values using Pandas

如何生成与其他列值相关的特定范围内的随机数?

我有一个带有列的数据框,比如说height ,我需要生成一个直径在一个范围内的额外列,并且直径应该与高度密切相关 这个怎么做?

我在这里所做的是在范围内生成随机高度值,每个物种都不同。 但是,我找不到在特定范围内的新列中生成直径值的解决方案。

我需要直径介于 'pinus_mugo' 的values 30 and 70之间以及'pinus_mugo' 'pinus_nigra'介于values 50 and 100之间。

import numpy as np
import pandas as pd

points.loc[points['species']== 'pinus_mugo', 'height'] = \
    np.round(np.random.uniform(35.0, 59.0,
                               size=(len(points[points['species']== 'pinus_mugo']), 1)), 2)

points.loc[points['species']== 'pinus_nigra', 'height'] = \
    np.round(np.random.uniform(20.0, 43.0,
                               size=(len(points[points['species']== 'pinus_nigra']), 1)), 2)

您可以定义一个函数,根据输入值为您提供输出值,并将此函数应用于 DataFrame 的列:

data = {'species':  ['pinus_mugo', 'pinus_nigra'],
        'height': [45, 30] }
df = pd.DataFrame(data)

def diameter(height):
  return random.uniform(0.025*height, 0.035*height)

df['diameter']  = df['height'].apply(lambda x: diameter(x))

这只是一个假设直径大约与高度成比例的示例,当然您可以定义任何其他随机函数。

您还可以定义一个函数,该函数在取决于物种(而不是高度)的范围内创建随机值,并将其应用于物种列:

def diameter2(species):
  min = max = 0
  if species == 'pinus_mugo': 
    min = 30 
    max = 70
  elif species == 'pinus_nigra':
    min = 50
    max = 100
  return random.randrange(min, max)

df['diameter2'] = df['species'].apply(lambda x: diameter2(x))

这完成了工作:

import numpy as np
from matplotlib.pyplot import scatter

# here I defined my desired values
xx = np.array([5, 35])
yy = np.array([8, 90])

means = [xx.mean(), yy.mean()]
stds = [xx.std() / 3, yy.std() / 3]
corr = 0.90         # correlation
covs = [[stds[0]**2          , stds[0]*stds[1]*corr],
        [stds[0]*stds[1]*corr,           stds[1]**2]]

m = np.random.multivariate_normal(means, covs, 760).T
scatter(m[0], m[1])

dataset = pd.DataFrame({'height': m[0], 'diameter': m[1]})
dataset['index'] = dataset.index
reference['index'] = reference.index

result = pd.concat([reference, dataset], axis=1)
scatter(result['height'], result['diameter'])

结果:

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM