[英]Creating an empty numpy with column names and types, and adding a first row
as title say, I want to create a empty numpy array, and adds first row, later will come more, sure, but first step first正如标题所说,我想创建一个空的 numpy 数组,并添加第一行,稍后会更多,当然,但第一步先
I try:我尝试:
myNp= np.empty( shape=(0,8),
dtype=[('city', np.str_),
('country_code', np.str_),
('latitude', np.single),
('longitude', np.single),
('timezone', np.str_),
('is_active' , np.bool_),
('is_underInv' , np.bool_),
('is_promoted' , np.bool_)
])
sampleCity=['myCity','ZA',51.51,-0.123,'Central TimeZone',True,True,True]
print(myNp)
print(sampleCity)
myNp= np.vstack((myNp, sampleCity))
print(myNp)
but all I got is invalid type promotion但我得到的只是无效的类型提升
You're close.你很近。 You get a structured or record array when you mix data types (string, floats, and bools).当您混合数据类型(字符串、浮点数和布尔值)时,您会得到一个结构化或记录数组。 You had the dtype correct, but the shape should be a tuple like this: shape=(nrows,)
.您的 dtype 正确,但形状应该是这样的元组: shape=(nrows,)
。 Also, you need to allocate a string size when you create an empty array.此外,您需要在创建空数组时分配字符串大小。 See modified code below.请参阅下面的修改代码。 It shows how add data to one row.它显示了如何将数据添加到一行。 You can also add data "column-wise" referencing the field name ( myNp['city'] = array_of_city_names
)您还可以添加引用字段名称的数据“按列”( myNp['city'] = array_of_city_names
)
dt = dtype=[('city', 'S20'),
('country_code', 'S20'),
('latitude', np.single),
('longitude', np.single),
('timezone', 'S20'),
('is_active' , np.bool_),
('is_underInv' , np.bool_),
('is_promoted' , np.bool_)
]
myNp = np.empty( shape=(8,), dtype=dt)
sampleCity = np.array([('myCity','ZA',51.51,-0.123,
'Central TimeZone',True,True,True)],
dtype=dt)
print(sampleCity)
myNp[0] = sampleCity
print(myNp[0])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.