How to set multiple color based on list of strings for network?

Viewed 118

I am trying to build a network where nodes have different color based on which list they belong to. At the moment there is only one list, list1, where elements found there are blue and other are green.

df['color'] = np.where(df.Var.isin(list1), "blue", "orange")

However I have another list, list2, which is important too, and I would like to distinguish also its elements with a colour (red), while the others keep the orange color. Summarising, what I would like to have is:

  • elements in list 1 in blue
  • elements in list 2 in red
  • remaining elements in orange.

How can I change my code accordingly?

2 Answers

If you are okay to stay with Pandas, you can use the apply method. With apply, you can use lambda and the ternary operator to choose the color based on Var.

import pandas as pd

d = {'Var':[1,2,3,4,5,6,7,8,9,0]}
lst1 = [1,2,3]  # blue
lst2 = [4,5,6]  # red

df = pd.DataFrame(d)

df['color'] = df['Var'].apply(lambda v : "blue" if v in lst1 else "red" if v in lst2 else "orange")

print(df.to_string(index=False))

Output

Var   color
   1    blue
   2    blue
   3    blue
   4     red
   5     red
   6     red
   7  orange
   8  orange
   9  orange
   0  orange

Use np.select

df['color'] = np.select([df.Var.isin(list1), df.Var.isin(list2)], ['blue','red'], 'orange')
Related