基于numpy和pandas的局部随机点

2024-05-19 11:03:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我的想法是尝试生成随机数据点(2D、x和y坐标),这些数据点彼此靠近,模拟以下场景:

  1. 我在一个物体上选择10个点。在
  2. 一个数据库中有200个这样的对象。在
  3. 我在所有物体的相同位置记录10个点的坐标。我的数据由200x10行组成,因此前10行代表第一个对象上10个采样点的坐标,接下来的10个代表第二个对象上的相同点,依此类推。在

在散点图中,对象中的点的集合应该很接近,但是它们不应该完全相同,或者相距太远。现在如果我使用普通随机生成器,大多数时候我会得到很多均匀分布的随机点。。。在

这是我尝试过的使用numpy、pandas和matplotlib的过程,以及对from{a1}post的多变量normal的一个很酷的用法。在

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import brewer2mpl as bmpl

#the part of the code I use for generating correlated ranges for points
#but I have used it for generating x,y coords as well but it didn`t work out 

corr = 0.95 
means = [200, 180]
stds = [10, 10]
covs = [[stds[0]**2, stds[0]*stds[1]*corr],[stds[0]*stds[1]*corr, stds[1]**2]]
coordstest = np.random.multivariate_normal(means, covs, 20)

#now the part for generating x and y coords

coords1x = np.random.uniform(coordstest[0,0], coordstest[0,1], 200)
coords1y = np.random.uniform(coordstest[1,0], coordstest[1,1], 200)
coords2x = np.random.uniform(coordstest[2,0], coordstest[2,1], 200)
coords2y = np.random.uniform(coordstest[3,0], coordstest[3,1], 200)
... up to 10

#them make them into two-column arrays

coords1 = np.vstack((coords1x, coords1y)).T
coords2 = np.vstack((coords2x, coords2y)).T
... up to 10

#and generate individual levels

individuals = np.arange(0,200) #generate individual levels
individuals = np.tile(individuals, 10)
individuals = pd.Series(individuals)

#finally generate pandas data frame and plot the results

allCoords = np.concatenate((coords1, coords2, coords3, coords4, coords5, coords6, coords7, coords8, coords9, coords10))
allCoords = pd.DataFrame(allCoords)
allCoords.columns = ['x','y']
allCoords['individuals'] = individuals
allCoords['index'] = allCoords.index.tolist()

allCoords = allCoords.sort_index(by=['individuals', 'index'])
del allCoords['index']
allCoords = allCoords.set_index(np.arange(0,2000))

plt.scatter(allCoords['x'], allCoords['y'], c = allCoords['individuals'], s = 40, cmap = 'hot')

这是分散的

Scatter plot

相同颜色的点应该局部分组。有什么办法做到的吗?在


Tags: the对象importpandasforindexasnp
1条回答
网友
1楼 · 发布于 2024-05-19 11:03:16

实际上,你会生成正态分布的区间,然后在区间内均匀分布点。不足为奇的是,最终得到的是非并置的点组。在

要获取并置的点组,应选择预期位置:

coordstest = np.vstack([np.random.uniform(150, 220, 20), 
                        np.random.uniform(150, 220, 20)]).T

然后根据它们生成点:

^{pr2}$

和阴谋

individuals = (np.arange(0,200).reshape(-1,1)*np.ones(10).reshape(1,-1)).flatten()
individuals = pd.Series(individuals)

allCoords = pd.DataFrame(coords, columns = ['x','y'])

plt.scatter(allCoords['x'], allCoords['y'], c = individuals, 
      s = 40, cmap = 'hot')

enter image description here

请注意,由于多元正态的协方差参数是非平凡的,所以点是以线性依赖关系生成的。如果你不需要它,你可以举例来说

coords = np.vstack([np.random.multivariate_normal(coordstest[i,:], 
               [[10,0],[0,10]], 200) for i in range(10)])

导致

enter image description here

相关问题 更多 >

    热门问题