python - 如何将 2 列数组(随机生成)转换为 DataFrame?
问题描述
使用 numpy 随机数生成器,生成居住在犹他州的 88,000 人的身高和体重的数组。平均身高1.75米,平均体重70公斤。假设标准差为 3。使用 column_stack 方法组合这两个数组并将其转换为 pandas DataFrame,第一列名为“height”,第二列名为“weight”
我得到了随机生成的数据。但是,我似乎无法将数组转换为 DataFrame
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)
解决方案
里面的数据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
推荐阅读
- r - 存储在列表中的数据帧的子集行号具有相同的整数值存储在列表中
- database - 如何切换到第二个数据库 Drupal
- mysql - 如何将mysqldump到外部服务器?
- mysql - 分类字段和时间戳列上的mysql分区,它是varchar
- ruby - 无法在 Mojave 上安装任何版本的 ruby - 内部 ranlib 命令失败
- java - 如何在 Android 中使用 Opencv 在图像上有效地应用 Canny 边缘检测器?
- angular - (Angular 2/4/5/6)ngx-international-phone-number 不显示正确的标志
- mysql - 商品被删除后,交易中的数据如何继续使用?
- python - 在对象上酸洗 lru_cached 函数
- python - 使用正则表达式将韩文文本解析为列表