How to color pd rows of DataFrame within groups?

Viewed 18

I have a dataframe with 2 columns:

area cluster
worlds 0.0
twisted 2.0
personnel 1.0
available 2.0
available 2.0

And I need to create a new column with colors assigned to each row on the condition that:

  • each cluster must have unique color within each area
  • colors of clusters in different areas may be repeated
  • color of one cluster in one area are not related to color of same cluster in another area

So the result may be something like:

area cluster color
worlds 0.0 green
twisted 2.0 blue
personnel 1.0 red
available 2.0 green
available 2.0 green

Any color scheme is appropriate

1 Answers

So you want just enumerate cluster within area, you can do:

list_colors = np.array(['green', 'blue', 'red', 'yellow'])
df['colors'] = list_colors[df.groupby(['area'])['cluster'].apply(lambda x: x.factorize()[0])]

This guarantees:

  • each cluster has unique color within each area

The other two points don't sound like restrictions to me. For reference, all the rows would get green color in your sample data.

Related