如何将 2 列数组(随机生成)转换为数据帧?



使用numpy随机数生成器,生成居住在犹他州的88,000人的身高和体重数组。 平均身高1.75米,平均体重70公斤。假设标准差为 3。 使用column_stack方法合并这两个数组,并将其转换为熊猫数据帧,第一列名为"高度",第二列名为"权重">

我得到了随机生成的数据。但是,我似乎无法将数组转换为数据帧

import numpy as np
import pandas as pd
height = np.round(np.random.normal(1.75, 3, 88000), 2)
weight = np.round(np.random.normal(70, 3, 88000), 2)
np_height = np.array(height)
np_weight = np.array(weight)
Utah = np.round(np.column_stack((np_height, np_weight)), 2)
print(Utah)
df = pd.DataFrame(
[[np_height],
[np_weight]],
index = [0, 1],
columns = ['height', 'weight'])
print(df)

您需要 2 列,但您将数据[[np_height],[np_weight]]作为 1 列传递。您可以将数据设置为dict

df = pd.DataFrame({'height':np_height,
'weight':np_weight},
columns = ['height', 'weight'])
print(df)

Utah中的数据已经处于合适的形状。为什么不使用它呢?

import numpy as np
import pandas as pd
height = np.round(np.random.normal(1.75, 3, 88000), 2)
weight = np.round(np.random.normal(70, 3, 88000), 2)
np_height = np.array(height)
np_weight = np.array(weight)
Utah = np.round(np.column_stack((np_height, np_weight)), 2)
df = pd.DataFrame(
data=Utah,
columns=['height', 'weight']
)
print(df.head())
height  weight
0    3.57   65.32
1   -0.15   66.22
2    5.65   73.11
3    2.00   69.59
4    2.67   64.95

最新更新