LoginSignup
2
2

More than 3 years have passed since last update.

Numpyで文字列をくっつける

Posted at

 普通にやる

import numpy as np

a = np.array(["a", "b", "c"])
b = np.array(["A", "B", "C"])
a+b

>>TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('<U1') dtype('<U1') dtype('<U1')

こうなる

np.objectを使う

import numpy as np

c = np.array(["a", "b", "c"], dtype=np.object)
d = np.array(["A", "B", "C"], dtype=np.object)
c+d

>>array(['aA', 'bB', 'cC'], dtype=object)

いけた

他の方法は?

mapを使おう

import numpy as np

a = np.array(["a", "b", "c"])
b = np.array(["A", "B", "C"])
np.array(list(map("".join, zip(a, b))))

>>array(['aA', 'bB', 'cC'], dtype='<U2')

結論

object型は便利です!

参考サイト

他の手法も紹介されている
https://stackoverrun.com/ja/q/2619737

Numpyのデータ型について
https://note.nkmk.me/python-numpy-dtype-astype/

2
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2