Arrays 使用分隔符连接numpy字符串数组
第一个问题:我有两个整数数组。我想创建一个字符串的numpy数组,其格式为“%03d\uu%04d”。例如,当我使用Arrays 使用分隔符连接numpy字符串数组,arrays,string,numpy,format,Arrays,String,Numpy,Format,第一个问题:我有两个整数数组。我想创建一个字符串的numpy数组,其格式为“%03d\uu%04d”。例如,当我使用 arr1 = np.arange(10) arr2 = arr1**2 strarr1 = np.char.mod("%03d",arr1) strarr2 = np.char.mod("%04d",arr2) strarr = strarr1 + '_' + strarr2 我得到 UFuncTypeError: ufunc 'add' did not contain a
arr1 = np.arange(10)
arr2 = arr1**2
strarr1 = np.char.mod("%03d",arr1)
strarr2 = np.char.mod("%04d",arr2)
strarr = strarr1 + '_' + strarr2
我得到
UFuncTypeError: ufunc 'add' did not contain a loop with signature
matching types (dtype('<U3'), dtype('<U3')) -> dtype('<U3')
UFuncTypeError:ufunc“add”不包含带有签名的循环
匹配类型(数据类型('
或包括‘’
In [88]: ['_'.join([i,j]) for i,j in zip(strarr1, strarr2)]
Out[88]:
['000_0000',
'001_0001',
'002_0004',
'003_0009',
'004_0016',
'005_0025',
'006_0036',
'007_0049',
'008_0064',
'009_0081']
In [89]: np.array(_)
Out[89]:
array(['000_0000', '001_0001', '002_0004', '003_0009', '004_0016',
'005_0025', '006_0036', '007_0049', '008_0064', '009_0081'],
dtype='<U8')
一般来说,与python字符串列表相比,numpy字符串数据类型提供的优势很少(如果有的话)。作为一种补充,Pandas的方法是:
import pandas as pd
import numpy as np
df=pd.DataFrame({'A':np.arange(10),
'B':np.arange(10)**2})
df['C']=df['A'].apply(str)+"_"+df['B'].apply(str)
哪个给
感谢hpaulj提供的非常有用的回复!
In [88]: ['_'.join([i,j]) for i,j in zip(strarr1, strarr2)]
Out[88]:
['000_0000',
'001_0001',
'002_0004',
'003_0009',
'004_0016',
'005_0025',
'006_0036',
'007_0049',
'008_0064',
'009_0081']
In [89]: np.array(_)
Out[89]:
array(['000_0000', '001_0001', '002_0004', '003_0009', '004_0016',
'005_0025', '006_0036', '007_0049', '008_0064', '009_0081'],
dtype='<U8')
In [91]: strarr1.astype(object)+'_'+strarr2.astype(object)
Out[91]:
array(['000_0000', '001_0001', '002_0004', '003_0009', '004_0016',
'005_0025', '006_0036', '007_0049', '008_0064', '009_0081'],
dtype=object)
import pandas as pd
import numpy as np
df=pd.DataFrame({'A':np.arange(10),
'B':np.arange(10)**2})
df['C']=df['A'].apply(str)+"_"+df['B'].apply(str)