Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas concatenate strings and numpy array

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading