Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Element-wise string concatenation in numpy

Is this a bug?

import numpy as np a1=np.array(['a','b']) a2=np.array(['E','F'])  In [20]: add(a1,a2) Out[20]: NotImplemented 

I am trying to do element-wise string concatenation. I thought Add() was the way to do it in numpy but obviously it is not working as expected.

like image 784
Dave31415 Avatar asked Mar 31 '12 18:03

Dave31415


People also ask

How do you concatenate two strings in an array in Python?

1- Using + operator Using + operator is the most common way to concatenate strings in python. You can concatenate two strings using this operator. The arguments should be string if you are using + operator to concatenate. Output will be an error “TypeError: unsupported operand type(s) for +: 'int' and 'str'”.

How do you concatenate 3 strings in Python?

Concatenation means joining strings together end-to-end to create a new string. To concatenate strings, we use the + operator. Keep in mind that when we work with numbers, + will be an operator for addition, but when used with strings it is a joining operator.

How do I concatenate two one direction arrays in Python?

Python NumPy concatenate arrays In numpy concatenate arrays we can easily use the function np. concatenate(). It can be used to concatenate two arrays either row-wise or column-wise. Concatenate function can take two or more arrays of the same shape and by default, it concatenates row-wise which means axis=0.

What is concatenate in NumPy?

concatenate. Advertisements. Concatenation refers to joining. This function is used to join two or more arrays of the same shape along a specified axis.


1 Answers

This can be done using numpy.core.defchararray.add. Here is an example:

>>> import numpy as np >>> a1 = np.array(['a', 'b']) >>> a2 = np.array(['E', 'F']) >>> np.core.defchararray.add(a1, a2) array(['aE', 'bF'],        dtype='<U2') 

There are other useful string operations available for NumPy data types.

like image 94
Mike T Avatar answered Sep 25 '22 07:09

Mike T