Just trying to generate a new column in a dataframe, which takes the value 1 or 0 based on a probability located in other columns in the same row.
with dummy data: df = pd.DataFrame({'a': [.1, .2, .3, .4], 'b': [.9, .8, .7, .6']})
I'm hoping to add a third column c, which in the first row for instance would have a .1 probability of being 1, and a .9 of being 0. And so on.
First attempt was defining a function and using apply:
def randomiser(x):
return np.random.choice([1,0], size=(1, 1), p=[df.loc[[x]]['a'], -df.loc[[x]]['b']])
df['probability'] = df.apply(lambda x: randomiser(x), axis=1)
However this would throw up an error about two many values being supplied to p, so I don't think it's iterating properly.
Second I tried a for loop:
for row in df.iterrows():
row['probability'] = np.random.choice([1,0], size=(1, 1), p=[df.loc[[row]]['a'], -df.loc[[row]]['b']])
But this leads to a TypeError complaining that series objects are mutable.
Finally I tried pulling the relevant columns out into tuples or lists, but with similar results.
Any thoughts? Thanks