0

I'm trying to add values to a pandas data frame based on the combinations of a user's and an agent's choices. Here's what i tried so far.

import random 
import numpy as np
import pandas as pd
from itertools import product 

ls = np.zeros((9,3))
choices = ['R','P','S']

df = pd.DataFrame(ls, columns = list(choices), index=[''.join(l) for l in 
product(choices, repeat=2)])
user_choices = ['R','S']
agent_choices = ['P','R']
i = 0 

while i < 1000:
i +=1 
user_choice = random.choice(choices)
agent_choice = random.choice(choices)
user_choices.append(user_choice)
agent_choices.append(agent_choice)
df[user_choices[i-1]][np.char.add(user_choices[i-2] ,agent_choices[i-2])] +=1

This results to getting an indexing error while the indexes exist.

Expected output should be as this example but obviously populated

Olive Yew
  • 351
  • 4
  • 13
  • please add some examples of your data set as well as expected output. https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples – Danail Petrov Jan 02 '21 at 12:31

1 Answers1

0

To fix your error, replace np.char.add with a simple string addition like stringA + stringB.

np.char.add returns a ndarray, which you can't index on. You want a simple string

Lukas Schmid
  • 1,895
  • 1
  • 6
  • 18