0

I have numpy array agent which contains 'y' or 'n'. I wanted to replace 'y' with 1 and 'n' with 0 and where something else is present say nan I want to assign -1. Script I wrote was

agent[agent=='y']=1
agent[agent=='n']=0
agent[(agent!='y') and (agent!='n')]=-1
agent=agent.astype(int)

It gave error "The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()" I understand I can use loops but I want to do this in one line in as simple way as I can

1
  • 2 * (agent == 'y').astype('int') + (agent == 'n').astype('int') - 1 works, but probably not a good idea :-) Commented Jun 24, 2016 at 23:37

3 Answers 3

3

Why not first make an array of -1, then fill with 1 and 0 based on agent

result = np.ones_like(agent, dtype=np.int) *-1
result [agent == 'y'] = 1
result [agent == 'n'] = 0
Sign up to request clarification or add additional context in comments.

1 Comment

Good idea. This feels cleaner than gradually changing the contents of an array with something of a different type.
2

First of all, given the order of assignments you have, if it worked, you'd have your whole array filled with -1's.

That being said, you can do:

agent[(agent != 0) & (agent != 1)] = -1

You can also consider using a masked array.

Comments

0

I would recommend creating a transformation function, f, that returns 0 for 'n', 1 for 'y', and -1 otherwise. Then I would do: desired_array = [f(cell) for cell in agent]

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.