0

I have a dataset like:

df["movie"] 
A
B
C
D

How to add another columns["genre"] with randomly assigned values from given list?

genres = ["action", "drama", "comedy"]

so that my df would look like:

movies genre
  A    action
  B    drama
  C    drama
  D    comedy
    ...

i've tried:

def addGenreColumn():
   for line in data:
       data["genre"] = random.choice(['action', 'comedy', 'drama'])
addGenreColumn()

but it will assign only one value from the list, like all 'action's or all 'comedy's. What is the proper way of dealing with that?

2 Answers 2

1

You could try with a list comprehension iterating over movies:

import random
import pandas as pd

data = pd.DataFrame({'movie':['A','B','C','D']})

def addGenre():
    data["genre"] = [random.choice(['action', 'comedy', 'drama']) for movie in data.movie]
    
addGenre()

print(data)

Output:

  movie   genre
0     A   drama
1     B  action
2     C  comedy
3     D  action
Sign up to request clarification or add additional context in comments.

Comments

1

You could use numpy.random.choice like:

data["genre"] = numpy.random.choice(genres, data["movie"].shape)

This will generate out of genres list with the shape as your first column so it can be assigned to the new column.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.