Matching array elements to dictionary keys in Python
I'm trying to match up elements in an array to dictionary keys. 开发者_运维百科 More specifically, I have a dictionary whose keys identify a disease state (a set of 0s and 1s) and an age (0-100) (ie, ((0,1,1,0), 35) is a key). I want to loop through these keys and get the corresponding values to put them in specific places in an array. The array that I have is structured such that the first four columns represent the disease state (0,1,1,0) and the fifth column represents the age. I want to have the sixth column be filled in with the information from the dictionary, given the corresponding disease state and age. Here is an example of the structure:
# Inputs
dis_state_list = [(0,0,0,1), (0,1,0,1), (0,1, 0,1), (0,0,0,0)]
ages = np.array([5, 10, 15, 20])
sims = np.zeros([5, 6])
# Make dictionary
dis_age_dict = {}
for a in ages:
for d in dis_state_list:
dis_age_dict[tuple(d), a] = np.random.normal(loc = 0, scale = .1, size = 1)
# Input sample values
sims[:, 4] = np.array([5, 10, 15, 15, 20])
sims [1,3] = 1
sims [2,1] = 1
To clarify, I want to fill in the last column of 'sims' with the items in the dictionary, based on the disease state and age of each sim.
With
>>> sims
array([[ 0., 0., 0., 1., 5., 0.],
[ 0., 1., 0., 1., 10., 0.],
[ 0., 1., 0., 1., 15., 0.],
[ 0., 0., 0., 0., 20., 0.]])
and
>>> d
{ ((0, 0, 0, 1), 5): -1,
((0, 0, 0, 0), 20): -4,
((0, 1, 0, 1), 15): -3,
((0, 1, 0, 1), 10): -2 }
(not actual display format, just put that way for easier viewing)
Do the following
for row in sims:
key = (tuple(row[:4]), row[4])
row[5] = d[key]
And then you get
>>> sims
array([[ 0., 0., 0., 1., 5., -1.],
[ 0., 1., 0., 1., 10., -2.],
[ 0., 1., 0., 1., 15., -3.],
[ 0., 0., 0., 0., 20., -4.]])
精彩评论