1

I am currently trying to loop over three lists at the same time:

list_weight = [0.9,0.3,0.6,0.4]
list_reliability = [0.8,0.5,0.2,0.8]
belief_CRED0 = [create_belief_matrix ('ACBA').iloc[0]] 

belief_CRED0
Out[40]: 
[1    0.562500
 2    0.562500
 3    0.391304
 4    0.391304
 Name: CRED0, dtype: float64]

First I created a nested loop:

for belief in belief_CRED0:
    for weight in list_weight:
        for reliability in list_reliability:
            m = [(1/(1+weight-reliability))*(weight*belief)]
print(m)

but the result was completely off. So I tried doing this instead:

for belief, weight, reliability in zip(belief_CRED0, list_weight, list_reliability):
    m = [(1/(1+weight-reliability))*(weight*belief)]
print(m)

but the result is wrong as well:

m
Out[42]: 
[1    0.460227
 2    0.460227
 3    0.320158
 4    0.320158
 Name: CRED0, dtype: float64]

From what comes out, it seems that the loop only uses the first weight and reliability from the corresponding lists (weight = 0.9 and reliability = 0.8).

The right output should be:

[1    0.460227
 2    0.210937
 3    0.16770171
 4    0.26086933

What should I do?

Dine
  • 47
  • 8
  • 1
    bit hard to answer that without knowing what `[create_belief_matrix ('ACBA').iloc[0]] ` is doing. – MSeifert Aug 17 '17 at 20:47
  • Your output will always just be the last `m` set. It's possible the correct answer is at a different part of the loop. – Brett Beatty Aug 17 '17 at 20:55
  • There is a bug in the for loop of the zip ... you say `m = [...]` ... you should rather just start `m` as an empty list ... and `m.append((1/ ...))`. That nested loop is wrong altogether. – motjuste Aug 17 '17 at 21:01
  • your variable m gets rewritten every one of the inner loop. If you're always using arrays of equal length then you should just use an index ie: for i in range(4): – Gavin Achtemeier Aug 17 '17 at 21:03

2 Answers2

2

Minor bug in your for loop over zip (which is the best way to do it BTW). Accumulate the result ... instead of keeping assigning to m.

m = []
for belief, weight, reliability in zip(belief_CRED0, list_weight, list_reliability):
    m.append(weight*belief/(1+weight-reliability))
print(m)
AChampion
  • 29,683
  • 4
  • 59
  • 75
motjuste
  • 131
  • 1
  • 5
1

If they were all pandas.Series or numpy.array then you could do this directly, e.g.:

>>> weight = pd.Series(list_weight, index=range(1, 5))
>>> reliability = pd.Series(list_reliability, index=range(1, 5))
>>> 1/(1+weight-reliability)*(weight*belief_CRED0)
1    0.460227
2    0.210937
3    0.167702
4    0.260869
dtype: float64

Similarly with numpy:

>>> weight = np.array(list_weight)
>>> reliability = np.array(list_reliability)
>>> 1/(1+weight-reliability)*(weight*belief_CRED0)
1    0.460227
2    0.210937
3    0.167702
4    0.260869
Name: CRED0, dtype: float64
AChampion
  • 29,683
  • 4
  • 59
  • 75
  • This is really efficient! I am going to change my code to use arrays now. Thank you! – Dine Aug 19 '17 at 18:25