Richard
Richard

Reputation: 65510

pandas: set cell value to index of current row?

I have a dataframe like this:

   a    b   c    country
0  5    7   11   Morocco
1  5    9   9    Nigeria
2  6    2   13   Spain

I would like to add a row d, which has the country name plus the index of the row (plus 1). Like this:

   a    b   c    country    d
0  5    7   11   Morocco    1. Morocco
1  5    9   9    Nigeria    2. Nigeria
2  6    2   13   Spain      3. Spain

How can I do this? I can do:

df['d'] = '1. ' + df['country']

But I'm having difficulty working out how to get the index of the row.

Upvotes: 1

Views: 166

Answers (1)

jezrael
jezrael

Reputation: 862431

Convert index values to strings and add column country:

df['d'] = (df.index + 1).astype(str) + '. ' + df['country']
print (df)
   a  b   c  country           d
0  5  7  11  Morocco  1. Morocco
1  5  9   9  Nigeria  2. Nigeria
2  6  2  13    Spain    3. Spain

Another solution for python 3.6+:

df['d'] = [f'{i + 1}. {x}' for i, x in enumerate(df['country'])]
#for versions below
#df['d'] = ['{}. {}'.format(i + 1, x) for i, x in enumerate(df['country'])]
print (df)
   a  b   c  country           d
0  5  7  11  Morocco  1. Morocco
1  5  9   9  Nigeria  2. Nigeria
2  6  2  13    Spain    3. Spain

Upvotes: 2

Related Questions