这确实是两个问题。

我有年龄间隔清单。对于每个间隔,都有一个对应的值。时间间隔和值在元组age_value_intervals列表中进行组织(请参见代码中的注释)。

我还有一个单独的年龄段列表,ages,我想知道这些值。

下面的代码尝试将值映射到给定的年龄。

现在到问题,


为了给value_map赋值,我使用ages遍历value_mapzip。然后,我尝试分配给value。这行不通。为什么?
我怀疑我使用的方法是否有效(如果可行)。有没有更好的方法来实现此映射?




import numpy as np

# List of tuples defining and age interval and the corresponing value for
# that interval. For instance (20, 30, 10) indicates that the age interval from
# 20 to 30 has the value 10
age_value_intervals = [(20, 30, 10),
                       (30, 35, 5),
                       (35, 42, 50),
                       (50, 56, 40),
                       (56, 60, 30)]

# The ages for which I would like to know the value
ages = [25, 30, 35, 40, 45, 50]

# Empty array used to stor the values for the corresponding age
value_map = np.empty(len(ages))
# I want the value to be nan if there is no known value
value_map[:] = np.nan

# Iterate over the ages I want to know the value for
for age, value in zip(ages, value_map):
    # Check if the age is in an interval for which the value is known
    for from_age, to_age, actual_value in age_value_intervals:
        if age >= from_age and age < to_age:
            # Assign the value to the value_map
            # This is were it falls apart (I guess...)
            value = actual_value
            # Move on to the next age since we got a match
            break

#Expected output
value_map = [10, 5, 50, 50, nan, 40]

最佳答案

我建议您将numpy.digitizedict一起使用。当值无法映射到范围时,您可以手动考虑实例。

import numpy as np

age_value_intervals = [(20, 30, 10),
                       (30, 35, 5),
                       (35, 42, 50),
                       (50, 56, 40),
                       (56, 60, 30)]

ages = np.array([25, 30, 35, 40, 45, 50])

bins = np.array([x[0] for x in age_value_intervals])
mapper = dict(enumerate([x[2] for x in age_value_intervals], 1))

res = np.array([mapper[x] for x in np.digitize(ages, bins)], dtype=float)

for idx in range(len(ages)):
    if not any(i <= ages[idx] <= j for i, j, k in age_value_intervals):
        res[idx] = np.nan


结果:

array([ 10.,   5.,  50.,  50.,  nan,  40.])

关于python - 分配给循环值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49410317/

10-12 18:04