[英]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.