两个 NumPy字符串数组的元素级连接
在本文中,我们将讨论如何按元素连接两个字符串数组
例子 :
Input :
A = ['Akash', 'Ayush', 'Diksha', 'Radhika']
B = ['Kumar', 'Sharma', 'Tewari', 'Pegowal']
Output :
A + B = [AkashKumar, AyushSharma, 'DikshTewari', 'RadhikaPegowal']
我们将使用numpy.char.add()方法。
Syntax : numpy.char.add(x1, x2)
Parameters :
- x1 : first array to be concatenated (concatenated at the beginning)
- x2 : second array to be concatenated (concatenated at the end)
Returns : Array of strings or unicode
示例 1:具有单个元素的字符串数组。
Python3
# importing library numpy as np
import numpy as np
# creating array as first_name
first_name = np.array(['Geeks'],
dtype = np.str)
print("Printing first name array:")
print(first_name)
# creating array as last name
last_name = np.array(['forGeeks'],
dtype = np.str)
print("Printing last name array:")
print(last_name)
# concat first_name and last_name
# into new array named as full_name
full_name = np.char.add(first_name, last_name)
print("\nPrinting concatenate array as full name:")
print(full_name)
Python3
# importing library numpy as np
import numpy as np
# creating array as first_name
first_name = np.array(['Akash', 'Ayush', 'Diksha',
'Radhika'], dtype = np.str)
print("Printing first name array:")
print(first_name)
# creating array as last name
last_name = np.array(['Kumar', 'Sharma', 'Tewari',
'Pegowal'], dtype = np.str)
print("Printing last name array:")
print(last_name)
# concat first_name and last_name
# into new array named as full_name
full_name = np.char.add(first_name, last_name)
print("\nPrinting concatenate array as full name:")
print(full_name)
输出 :
Printing first name array:
['Geeks']
Printing last name array:
['forGeeks']
Printing concatenate array as full name:
['GeeksforGeeks']
示例 2:具有多个元素的字符串数组。
Python3
# importing library numpy as np
import numpy as np
# creating array as first_name
first_name = np.array(['Akash', 'Ayush', 'Diksha',
'Radhika'], dtype = np.str)
print("Printing first name array:")
print(first_name)
# creating array as last name
last_name = np.array(['Kumar', 'Sharma', 'Tewari',
'Pegowal'], dtype = np.str)
print("Printing last name array:")
print(last_name)
# concat first_name and last_name
# into new array named as full_name
full_name = np.char.add(first_name, last_name)
print("\nPrinting concatenate array as full name:")
print(full_name)
输出 :
Printing first name array:
['Akash' 'Ayush' 'Diksha' 'Radhika']
Printing last name array:
['Kumar' 'Sharma' 'Tewari' 'Pegowal']
Printing concatenate array as full name:
['AkashKumar' 'AyushSharma' 'DikshaTewari' 'RadhikaPegowal']