0

I have two lists

Countrylist = ['USA', 'INDIA', 'SINGAPORE','CHINA','MALAYSIA']
COLORLIST = ['#F1F326', '#D95969', '#D4526E', '#250591', '#FDBB2B']

and I have a df with 4 columns:

Country Category AVGSPEED AVGVELOCITY
USA     High     345       4634
INDIA   Low      4363      435346
USA     Low      345       346346
CHINA   High     3462      23423
CHINA   Medium   46346     46346

I want add a new column to the dataframe such that the color from the list gets mapped to the country seen in the dataframe. One way am thinking is creating a dict between the two lists, and then mapping the key value to the country column in the dataframe.

2 Answers 2

1

Use Series.map by dictionary created by zip of both lists:

Countrylist = ['USA', 'INDIA', 'SINGAPORE','CHINA','MALAYSIA']
COLORLIST = ['#F1F326', '#D95969', '#D4526E', '#250591', '#FDBB2B']

df['Color'] = df['Country'].map(dict(zip(Countrylist, COLORLIST)))
print (df)
  Country Category  AVGSPEED  AVGVELOCITY    Color
0     USA     High       345         4634  #F1F326
1   INDIA      Low      4363       435346  #D95969
2     USA      Low       345       346346  #F1F326
3   CHINA     High      3462        23423  #250591
4   CHINA   Medium     46346        46346  #250591
Sign up to request clarification or add additional context in comments.

Comments

1

Yes, it's map:

df['color'] = df['Country'].map(pd.Series(COLORLIST, index=Countrylist))

Output:

  Country Category  AVGSPEED  AVGVELOCITY    color
0     USA     High       345         4634  #F1F326
1   INDIA      Low      4363       435346  #D95969
2     USA      Low       345       346346  #F1F326
3   CHINA     High      3462        23423  #250591
4   CHINA   Medium     46346        46346  #250591

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.