[SOLVED] How can I assign data from a list to pandas DataFrame?

Issue

I created a df with different courses, and list with prices. What I need is to assign prices to all courses in dataframe – for example, all English courses in df should have first price from price list, all finance courses should have second price from price list etc. (order doesn’t matter). Any suggestions?

import random
import pandas as pd
import numpy as np

courses_list = ['Programming', 'Data Science', 'Data Analytics', 'Business Management', 'English', 'Design', 'Finance']
courses = []
for i in range(500):
    courses.append(random.choice(courses_list))

price = np.random.randint(50000, 100000, 7)
name = np.arange(500)

df = pd.DataFrame({'used_id':name,
                   'course_name':courses})
df

Solution

Use dict comprehension with Series.map:

# Create a dict with key as course_name and value as price
In [2358]: course_price = {i:price[c] for c, i in enumerate(courses_list)}

# Use `map` function to map the price for each course from dict to df 
In [2360]: df['price'] = df.course_name.map(course_price)

In [2361]: df
Out[2361]: 
     used_id          course_name  price
0          0  Business Management  56022
1          1       Data Analytics  85224
2          2          Programming  64843
3          3  Business Management  56022
4          4         Data Science  65005
..       ...                  ...    ...
495      495  Business Management  56022
496      496       Data Analytics  85224
497      497              English  95012
498      498  Business Management  56022
499      499       Data Analytics  85224

[500 rows x 3 columns]

Answered By – Mayank Porwal

Answer Checked By – Terry (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *