0

I have this code:

import numpy as np

result = {}
result['depth'] = [1,1,1,2,2,2]
result['generation'] = [1,1,1,2,2,2]
result['dimension'] = [1,2,3,1,2,3]
result['data'] = [np.array([0,0,0]), np.array([0,0,0]), np.array([0,0,0]), np.array([0,0,0]), np.array([0,0,0]), np.array([0,0,0])]

for v in np.unique(result['depth']):
    temp_v = np.where(result['depth'] ==  v)
    values_v = [result[string][temp_v] for string in result.keys()]
    this_v = dict(zip(result.keys(), values_v))

in which I want to create a new dictcalled 'this_v', with the same keys as the original dict result, but fewer values.

The line:

values_v = [result[string][temp_v] for string in result.keys()]

gives an error

TypeError: list indices must be integers, not tuple

which I don't understand, since I can create ex = result[result.keys()[0]][temp_v] just fine. It just does not let me do this with a for loop so that I can fill the list.

Any idea as to why it does not work?

1
  • 1
    np.where returns a tuple Commented Aug 23, 2018 at 11:28

1 Answer 1

2

I'm not sure what you are trying to achieve but I could solve your issue:

np.where is returning a tuple, so to access you need to do give the index temp_v[0]. Also the value of the tuple is an array so to loop over the value you need to run another loop a for a in temp_v[0] which helps you you access the value.

import numpy as np

result = {}
result['depth'] = [1,1,1,2,2,2]
result['generation'] = [1,1,1,2,2,2]
result['dimension'] = [1,2,3,1,2,3]
result['data'] = [np.array([0,0,0]), np.array([0,0,0]), np.array([0,0,0]), np.array([0,0,0]), np.array([0,0,0]), np.array([0,0,0])]

for v in np.unique(result['depth']):
    temp_v = np.where(result['depth'] ==  v)
    values_v = [result[string][a] for a in temp_v[0] for string in result.keys()]
    this_v = dict(zip(result.keys(), values_v))
Sign up to request clarification or add additional context in comments.

6 Comments

Hey, thanks. I actually found a better way by using a mask. Now I have <code> temp_v = (result['depth'] == v) values_v = [result[string][temp_v] for string in result.keys()]</code> but it still gives an error, "only integer scalar arrays can be converted to a scalar index"
try this line values_v = [result[string][a] for a in temp_v[0] for string in result.keys()]
That works, but I'm trying to recude the number of for loops. Hence the masking idea
could you edit your code in the question, I can help you then
|

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.