亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用包含數組的單個結構化元素創建數組

使用包含數組的單個結構化元素創建數組

aluckdog 2023-10-06 13:44:24
我有一個像這樣的數據類型:>>> dt = np.dtype([('x', object, 3)])>>> dtdtype([('x', 'O', (3,))])一個名為“x”的字段,包含三個指針。我想用這種類型的單個元素構造一個數組:>>> a = np.array([(['a', 'b', 'c'])], dtype=dt)>>> b = np.array([(np.array(['a', 'b', 'c'], dtype=object))], dtype=dt)>>> c = np.array((['a', 'b', 'c']), dtype=dt)>>> d = np.array(['a', 'b', 'c'], dtype=dt)>>> e = np.array([([['a', 'b', 'c']])], dtype=dt)所有這五個語句都會產生相同的錯誤結果:array([[(['a', 'a', 'a'],), (['b', 'b', 'b'],), (['c', 'c', 'c'],)]],      dtype=[('x', 'O', (3,))])如果我嘗試刪除內部列表/數組,則會收到錯誤:>>> f = np.array([('a', 'b', 'c')], dtype=dt)ValueError: could not assign tuple of length 3 to structure with 1 fields.同樣的錯誤發生在>>> g = np.array(('a', 'b', 'c'), dtype=dt)我已經用完了所有可能的組合來嘗試。我正在尋找的結果是 array([(['a', 'b', 'c'],)], dtype=[('x', 'O', (3,))])如何創建一個包含指定數據類型的一個元素的數組?到目前為止,我發現的唯一方法是手動分配:z = np.empty(1, dtype=dt)z['x'][0, :] = ['a', 'b', 'c']或者z[0]['x'] = ['a', 'b', 'c']np.array對于應該能夠開箱即用的東西來說,這似乎是一個不必要的解決方法。
查看完整描述

1 回答

?
暮色呼如

TA貢獻1853條經驗 獲得超9個贊

In [44]: dt = np.dtype([('x', object, 3)])   # corrected

In [45]: dt

Out[45]: dtype([('x', 'O', (3,))])

In [46]: np.empty(3, dt)

Out[46]: 

array([([None, None, None],), ([None, None, None],),

       ([None, None, None],)], dtype=[('x', 'O', (3,))])

In [47]: np.array([(['a','b','c'],)], dt)

Out[47]: array([(['a', 'b', 'c'],)], dtype=[('x', 'O', (3,))])

輸入格式應與輸出格式匹配。


In [48]: arr = np.empty(3, dt)

In [49]: arr['x']

Out[49]: 

array([[None, None, None],

       [None, None, None],

       [None, None, None]], dtype=object)

In [50]: arr['x'][0]

Out[50]: array([None, None, None], dtype=object)

In [51]: arr['x'][0] = ['a','b','c']

In [52]: arr

Out[52]: 

array([(['a', 'b', 'c'],), ([None, None, None],), ([None, None, None],)],

      dtype=[('x', 'O', (3,))])


查看完整回答
反對 回復 2023-10-06
  • 1 回答
  • 0 關注
  • 120 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號