0

My dataset has three columns: State, Food, and State_New. My goal is to create a forth column but return a random value based on an established list of values. Initially, I was trying to do a vlookup and randbetween function in excel, where my goal was to return a random value from a list, so long as my first criteria matched - but that did not work (it always chose the first value to return).

Below is an example. So, the unique values for State PA are: Pop and Soda, while for CA it is Burger and Fries (the State and Food column link together). The Food_New column should first look at the State_New column, find the same state name in State column, and then randomly pick a value from the Food column.

My actual dataset is quite large with multiple different combinations. I'm not sure if I should use random.choice(list) function or something else.

Input:

State Food   State_New
CA    Burger PA      
CA    Fries  CA       
PA    Soda   CA      
PA    Pop    PA
PA    Soda   PA  

Output:

State Food   State_New Food_New
CA    Burger PA        Pop
CA    Fries  CA        Fries
PA    Soda   CA        Fries
PA    Pop    PA        Pop
PA    Soda   PA        Soda

The output (Food_New) column, should potentially change anytime I rerun the code.

0

1 Answer 1

1

Build the list of Food choices from State and pick a value according the list of Food from State_New:

df['Food_New'] = df['State_New'].map(df.groupby('State')['Food'].unique()) \
                                .apply(np.random.choice)
>>> df
  State    Food State_New Food_New
0    CA  Burger        PA      Pop
1    CA   Fries        CA   Burger
2    PA    Soda        CA    Fries
3    PA     Pop        PA      Pop
4    PA    Soda        PA     Soda
Sign up to request clarification or add additional context in comments.

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.