2

Given the following example:

import pandas as pd
data = pd.DataFrame({'ID' : [1, 1, 2, 4, 4, 4, 4, 4, 11, 11, 16, 17, 17, 19]})

>>> data
    ID
0    1
1    1
2    2
3    4
4    4
5    4
6    4
7    4
8   11
9   11
10  16
11  17
12  17
13  19

How can I simply renumber thet values as a column in a dataframe so that they are sequential, i.e. the output of data is:

>>> data
    ID
0    1
1    1
2    2
3    3
4    3
5    3
6    3
7    3
8    4
9    4
10   5
11   6
12   6
13   7

Thanks

1 Answer 1

3

One way would be to create a dict mapping the unique values in your ID column to your new sequential values and then call map passing in this dict:

In [48]:
d = dict(zip(data['ID'].unique(), np.arange(1, len(data['ID'].unique()) + 1)))
d

Out[48]:
{1: 1, 2: 2, 4: 3, 11: 4, 16: 5, 17: 6, 19: 7}

In [49]:
data['ID'] = data['ID'].map(d)
data

Out[49]:
    ID
0    1
1    1
2    2
3    3
4    3
5    3
6    3
7    3
8    4
9    4
10   5
11   6
12   6
13   7

EDIT

Actually a better way would be to call rank on the column and pass param dense:

In [56]:

data['ID'] = data['ID'].rank('dense')
data
Out[56]:
    ID
0    1
1    1
2    2
3    3
4    3
5    3
6    3
7    3
8    4
9    4
10   5
11   6
12   6
13   7
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.