[PYTHON] Stick strings together with Numpy

Do it normally

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

Will be like this

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

I got it

Any other way?

Let's use 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')

Conclusion

The object type is convenient!

Reference site

Other methods are also introduced https://stackoverrun.com/ja/q/2619737

About Numpy data types https://note.nkmk.me/python-numpy-dtype-astype/

Recommended Posts

Stick strings together with Numpy
Getting Started with Numpy
Learn with Cheminformatics NumPy
Matrix concatenation with Numpy
Hamming code with numpy
Regression analysis with NumPy
Extend NumPy with Rust
Kernel regression with Numpy only
I wrote GP with numpy
CNN implementation with just numpy
[Python] Calculation method with numpy
Try matrix operation with NumPy
Diffusion equation animation with NumPy
Debt repayment simulation with numpy
Implemented SMO with Python + NumPy
Handle numpy arrays with f2py
How to separate strings with','
Use OpenBLAS with numpy, scipy
Python3 | Getting Started with numpy
Implementing logistic regression with NumPy
Perform least squares fitting with numpy.
Draw a beautiful circle with numpy
Implement Keras LSTM feedforward with numpy
[Beginner] Extract character strings with Python
Manipulating strings with pandas group by
Extract multiple elements with Numpy array