0

I have a situation in which I would like to do the following:

import numpy as np
type1 = np.dtype([('col1', 'i'), ('col2', 'i')])
type2 = np.dtype([('cols', type1), ('info', 'S32')])
data = np.zeros(10, type2)

# The following doesn't work, but I want to do something similar
index = ['cols']['col1']
# Set column ['cols']['col1'] to 5
data[index] = 5

# I can only get this to work if I do the following: 
index = "['cols']['col1']"
eval('data' + index '= 5') # kinda scary

This doesn't work, but I found a workaround using the exec function but that feels pretty hacky. Does anyone have any suggestions how to programmatically create an index for nested structured numpy datatypes?

Thanks

3
  • Why can't you use data['cols']['col1'] =5 ? Commented Nov 2, 2015 at 21:56
  • because I need to be able to define the indices in a separate step unfortunately. Commented Nov 2, 2015 at 21:57
  • 1
    What if you defined them like index1, index2 = 'cols', 'col1' and used data[index1][index2] ? Commented Nov 2, 2015 at 22:00

1 Answer 1

1

This would work:

index = ['cols', 'col1']
data[index[0]][index[1]] = 5

UPDATE

This allows setting of values at any depths:

def set_deep(obj, names, value):
    if len(names) > 1:
        obj = obj[names[0]]
        if len(names) > 2:
            for name in names[1:-1]:
                obj = obj[name]
    obj[names[-1]] = value

Usage:

set_deep(data, ['cols', 'col1'], 5)

set_deep(data, ['a', 'b', 'c', 'd'], 5)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, this is close to what I might end up having to use, but have structured datatypes that are not just 2 deep. I might have things defined like data['a']['b']['c']['d']. In this case I guess I could do a for loop or something.
I think this might be as close as we can get without using the exec statement.

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.