繁体   English   中英

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

[英]How do I convert 2 column array(randomly generated) to a DataFrame?

使用numpy随机数生成器,生成居住在犹他州的88,000人的身高和体重数组。 平均高度为1.75米,平均重量为70kg。 假设存在3的标准偏差。使用column_stack方法将这两个数组合并,并将其转换为第一列名为“ height”,第二列称为“ weight”的pandas DataFrame。

我已经获得了随机生成的数据。 但是,我似乎无法将数组转换为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)

您需要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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM