Daniel Holmes
Daniel Holmes

Reputation: 2002

Use row index number as string in new column rows

I would like to add a column to my DataFrame in which each row includes a string with the row index + 1. This is what I have attempted:

>>> import pandas as pd
>>> df = pd.DataFrame.from_records([{'some_column': 'foo'}, {'some_column': 'bar'}])
>>> df['new_column'] = f'some string {df.index + 1}'

But is just gives:

>>> df['new_column']
0    some string RangeIndex(start=1, stop=3, step=1)
1    some string RangeIndex(start=1, stop=3, step=1)

How can I achieve the desired result?

Upvotes: 1

Views: 385

Answers (1)

ansev
ansev

Reputation: 30920

Use:

df.assign(new_column='some string '+(df.index+1).astype(str))
  some_column     new_column
0         foo  some string 1
1         bar  some string 2

or

df['new_column']='some string ' + (df.index+1).astype(str)

Alternative

(df.rename_axis('new_column')
   .reset_index()
   .assign(new_column=lambda x: 'some string '+ 
                                x['new_column'].add(1)
                                               .astype(str))

Upvotes: 2

Related Questions