NumPy中两个字符串数组的元素串联

NumPy中两个字符串数组的元素串联

在这篇文章中,我们将讨论如何将两个字符串数组的元素连接起来。

示例 :

输入:
A = [‘Akash’, ‘Ayush’, ‘Diksha’, ‘Radhika’]
B = [‘Kumar’, ‘Sharma’, ‘Tewari’, ‘Pegowal’]

输出:
A + B = [AkashKumar, AyushSharma, ‘DikshTewari’, ‘RadhikaPegowal’]

我们将使用numpy.char.add()方法。

语法 : numpy.char.add(x1, x2)
参数 :

  • x1:第一个要连接的数组(在开始时连接)
  • x2 : 第二个要连接的数组(在最后连接)

返回:字符串或unicode的数组

例子1:有一个元素的字符串数组。

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

输出 :

Printing first name array:
['Geeks']
Printing last name array:
['forGeeks']

Printing concatenate array as full name:
['GeeksforGeeks']

例子2:有多个元素的字符串数组。

# 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']

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程