gpt4 book ai didi

python - 创建随机数据库并将其从 numpy 转换为 pandas

转载 作者:行者123 更新时间:2023-11-30 21:54:17 27 4
gpt4 key购买 nike

我想创建随机数据库。在数据库中我想创建坐标,所以在编辑器中我可以绘制它,这意味着每个点都有 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)

我收到的错误:

Exception: Data must be 1-dimensional

我还尝试了其他方法来使其成为数据帧,但它不起作用,我相信这是我缺少的一些小东西。

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

最佳答案

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

示例:

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

这就是破坏 pd.DataFrame 调用的原因。因此,要解决此问题,您需要将形状参数传递为 (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)

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

#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})

关于python - 创建随机数据库并将其从 numpy 转换为 pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59352797/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com