首页 > 解决方案 > 如何将 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)

标签: pythonpython-3.xpandasnumpy

解决方案


里面的数据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

推荐阅读