python - 创建随机数据库并将其从 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)
我收到的错误:
例外:数据必须是一维的
我也尝试过其他方法来制作它的数据框,但它没有用,我相信这是我遗漏的一些小东西。
我的最终目标是从这些数组创建数据框。
解决方案
您调用的方式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 处的值设置为索引。最终代码将如下所示:index
pd.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})
推荐阅读
- azure - 从 .NET Core 向 Application Insights 跟踪添加自定义维度
- android - 如何在 Android 上的 EditText 上设置属性和 actionEvent
- javascript - 页面在初始页面加载时有效,但如果我刷新页面,我会收到 Zeit、Nextjs 和现在的 404 错误
- mysql - 无法诊断 MySQL 存储过程的问题
- java - 我的自定义信号量似乎在我的程序中不起作用
- python - 为张量流分割模型获取混淆矩阵的有效方法是什么?
- java - 如何将txt读取到arrayList然后返回arrayList?
- python - (Jupyter Notebook) ModuleNotFoundError: No module named 'pandas'
- javascript - 旋转相机以查看三个.js 中的选定对象
- python - 如何按工作表名称将整个工作表从一本书移动到另一本工作簿