I want to append values to array but want to separate when the index is 0 or 1. For example,
index=np.array([0,1,0,1,0,1,0,1,0,1])
new_values = np.array([5,7,9,4,6,3,5,2,9,5])
array=[]
Here I want to run through the index array and create a new array (called 'array') that will receive new values and group them when the index is 0 or 1. I should get an output something like this,
array = ([0: 5,9,6,5,9 ; 1: 7,4,3,2,5])
I tried using dictionaries but I guess it didn't work.
How should I do this ?
CodePudding user response:
You can initialize a dictionary and then fill it with a zip of the two arrays, like this:
d = dict()
for k,v in zip(index, new_values):
d[k] = d[k] [v] if k in d else []
CodePudding user response:
you can use dictionary to solve this problem. we will insert more than one values to a key. first we will create an array of sets to store the values related to the key.
s = []
for i in range(len(new_values)):
s.append((index[i],new_values[i]))
print(s)
not we will have something like this s = [(0, 5), (1, 7), (0, 9), (1, 4), (0, 6), (1, 3), (0, 5), (1, 2), (0, 9), (1, 5)]
now
data_dict = {}
for x in s:
data_dict.setdefault(x[0],[]).append(x[1])
print(data_dict)
output :- {0: [5, 9, 6, 5, 9], 1: [7, 4, 3, 2, 5]}