Skip to content
Advertisement

Mapping values between numpy arrays and categorizing it

Novice in python! A numpy array A of 1000 elements consists of fixed values between -100 to +100. These 201 values are nothing but categories. Another numpy array B has the approximations of the values for each category of A. Both A and B are of same length. For example A=[-100, -100, -88, 87, 85, 32, 32, 32] and corresponding B=[-100.3, -100.1, -86.5, 87.3, 85.5, 32.6,32.1,32.5]. I want to get the corresponding approximated data for each category. In the above example

for -100:-100.3, -100.1  
for 32:32.1,32.6,32.5

I could not seem to get it working with dictionary and zipping

Advertisement

Answer

You are on a good truck thinking about dictionaries and zip. What you really want is to iterrate through your A unique values and append values to a dict with keys these values. Using list comprehension it can be almost an one-liner. For example:

A = [-100, -100, -88, 87, 85, 32, 32, 32]
B = [-100.3, -100.1, -86.5, 87.3, 85.5, 32.6, 32.1, 32.5]

values_dict = {i: [] for i in set(A)}  # Initialize dictionary with empty lists
[values_dict[pair[0]].append(pair[1]) for pair in zip(A, B)]  # Append values to corresponding key.

print(values_dict)

Which prints:

{32: [32.6, 32.1, 32.5], -88: [-86.5], 85: [85.5], 87: [87.3], -100: [-100.3, -100.1]
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement