1

My questions is, if in a dataframe of pandas, I have a column like this, ['black'.'black','red','orange','red'] . I need to convert this array to, [1,1,2,3,2]

How to make this in python (is there any standard operation to do this in numpy or pandas)

4 Answers 4

1

There is a map function for pandas for doing this, so you would just do something like:

In [71]:

df = pd.DataFrame({'col':['black','black','red','orange','red']})
df
Out[71]:
      col
0   black
1   black
2     red
3  orange
4     red

[5 rows x 1 columns]
In [74]:

col_map = {'black':1,'red':2,'orange':3}
df['col_id'] = df['col'].map(col_map)
df
Out[74]:
      col  col_id
0   black       1
1   black       1
2     red       2
3  orange       3
4     red       2

[5 rows x 2 columns]

This will assign a new column 'col_id' to your dataframe and map the string values to their int counterparts.

0

The Factor class may help you. This answer seems to be about what you're looking for.

0

Use OrderedDict to preserve list order, but remove duplicates:

>>> l = ['black', 'black','red','orange','red']
>>> from collections import OrderedDict
>>> [OrderedDict.fromkeys(l).keys().index(i) + 1 for i in l]
[1, 1, 2, 3, 2]
2
  • But from the question we don't know whether the first element in the list of colors is supposed to correspond to the number one. It could correspond to 42 as far as I understand it.
    – timgeb
    Jul 3, 2014 at 20:50
  • Anything is possible, but the implication seemed pretty clear that the indices (column numbers) were determined by the position they first occur, excluding duplicates.
    – Ben
    Jul 3, 2014 at 21:17
0

The numpy answer is np.unique with return_inverse

>>> np.unique(['black','black','red','orange','red'], return_inverse=True)
(array(['black', 'orange', 'red'], 
      dtype='|S6'), array([0, 0, 2, 1, 2]))

This assign integers to the alphabetically sorted unique content.

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.