简体   繁体   English

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

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

Using a numpy random number generator, generate arrays on height and weight of the 88,000 people living in Utah. 使用numpy随机数生成器,生成居住在犹他州的88,000人的身高和体重数组。 The average height is 1.75 metres and the average weight is 70kg. 平均高度为1.75米,平均重量为70kg。 Assume standard deviation on 3. Combine these two arrays using column_stack method and convert it into a pandas DataFrame with the first column named as 'height' and the second column named as 'weight' 假设存在3的标准偏差。使用column_stack方法将这两个数组合并,并将其转换为第一列名为“ height”,第二列称为“ weight”的pandas DataFrame。

I've gotten the randomly generated data. 我已经获得了随机生成的数据。 However, I can't seem to convert the array to a 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)

You want 2 columns, yet you passed data [[np_height],[np_weight]] as 1 column. 您需要2列,但是将数据[[np_height],[np_weight]]传递为1列。 You can set the data as dict . 您可以将数据设置为dict

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

The data in Utah is already in a suitable shape. Utah的数据已经处于合适的状态。 Why not use that? 为什么不使用它?

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