简体   繁体   中英

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

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,) . 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 )

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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