I have this:
n = 5
df = pandas.DataFrame(dict(j=numpy.repeat(0, n)))
df['j'] = 'prefix-'
df['j'] += numpy.arange(n).astype('U')
df['j'] += '-suffix'
print(df)
which produces:
j
0 prefix-0-suffix
1 prefix-1-suffix
2 prefix-2-suffix
3 prefix-3-suffix
4 prefix-4-suffix
Is there a way to do this (reasonably) in one line?
I tried:
df['j'] = 'prefix-' + numpy.arange(n).astype('U') + '-suffix'
but that resulted in this error:
numpy.core._exceptions._UFuncNoLoopError: ufunc 'add' did not contain a loop with signature matching types (dtype('<U7'), dtype('<U21')) -> None
>Solution :
Convert as string using astype and pd.RangeIndex
# df['j'] = 'prefix-' + df['j'].astype(str) + '-suffix'
df['j'] = 'prefix-' + pd.RangeIndex(n).astype(str) + '-suffix'
print(df)
# Output
j
0 prefix-0-suffix
1 prefix-1-suffix
2 prefix-2-suffix
3 prefix-3-suffix
4 prefix-4-suffix