首页 > 解决方案 > 创建随机数据库并将其从 numpy 转换为 pandas

问题描述

我想创建随机数据库。在数据库中我想创建坐标,所以在编辑中我可以绘制它,意思是,每个点都应该有 X 和 Y 坐标。

我已经为一组点创建了数据,但它在 numpy 中,我希望它在 pandas 中并且我不断收到错误。

这就是我创建它的方式:

#database 1
# defining the mean 
mu = 0.5
# defining the standard deviation  
sigma = 0.1

# The random module uses the seed value as a base  
# to generate a random number. If seed value is not  
# present, it takes the system’s current time. 
np.random.seed(0) 

# define the x co-ordinates 
X = np.random.normal(mu, sigma, (395, 1)) 

# define the y co-ordinates 
Y = np.random.normal(mu * 2, sigma * 3, (395, 1))

index=[X,Y]

##here I get all the errors 

df = pd.DataFrame({'X': X, 'Y': Y}, index=index)

我收到的错误:

例外:数据必须是一维的

我也尝试过其他方法来制作它的数据框,但它没有用,我相信这是我遗漏的一些小东西。

我的最终目标是从这些数组创建数据框。

标签: pythonpandasnumpydataframe

解决方案


您调用的方式np.random.normal是创建 shape 数组(395, 1)。这意味着您正在创建一个包含 1 个元素的 395 个数组的数组。

例子:

array([[0.67640523],
   [0.54001572],
   [0.5978738 ],
   [0.72408932],
   [0.6867558 ],
   [0.40227221],..])

这就是破坏 pd.DataFrame 调用的原因。因此,要解决这个问题,您需要将 shape 参数作为 (395) 或简单地 395 来创建一维数组。

#database 1
# defining the mean 
mu = 0.5
# defining the standard deviation  
sigma = 0.1

# The random module uses the seed value as a base  
# to generate a random number. If seed value is not  
# present, it takes the system’s current time. 
np.random.seed(0) 

# define the x co-ordinates 
X = np.random.normal(mu, sigma, (395)) 

# define the y co-ordinates 
Y = np.random.normal(mu * 2, sigma * 3, (395))

index=[X,Y]

##here I get all the errors 

df = pd.DataFrame({'X': X, 'Y': Y}, index=index)

我还建议您在调用时删除该行index=[X,Y]和参数,因为它对我没有任何意义。您正在将 X 和 Y 处的值设置为索引。最终代码将如下所示:indexpd.DataFrame

#database 1
# defining the mean 
mu = 0.5
# defining the standard deviation  
sigma = 0.1

# The random module uses the seed value as a base  
# to generate a random number. If seed value is not  
# present, it takes the system’s current time. 
np.random.seed(0) 

# define the x co-ordinates 
X = np.random.normal(mu, sigma, 395) 
print(X.shape)

# define the y co-ordinates 
Y = np.random.normal(mu * 2, sigma * 3, 395)
print(Y.shape)


##here I get all the errors 

df = pd.DataFrame({'X': X, 'Y': Y})

推荐阅读