'Loop through dictionary to create a dataframe from function without repeating keys
dict = {'A': ndarray_1, 'B': ndarray_2, 'C': ndarray_3}
I'm trying, without success so far, to use a for loop it in a callable function of a package that return two results and make a dataframe like this:
Letter | Letter | Result 1 | Result 2
A | B | result1(ndarray_1,ndarray_2) | result2(ndarray_1,ndarray_2)
A | C | result1(ndarray_1,ndarray_3) | result2(ndarray_1,ndarray_3)
B | C | result1(ndarray_2,ndarray_3) | result2(ndarray_2,ndarray_3)
I'm having trouble acessing the value of each key to use in the function and not repeating ({A,B}, {B,A}, for example)
Solution 1:[1]
There might be built-in functions to do this, but here's a simple way to do it from scratch:
- Create an ordered list of the keys:
keys = dict.keys() - Loop through the indices of the ordered list:
for i in range(len(keys)): - Inside that, loop through the indices starting at i+1:
for j in range(i + 1, len(keys)): - Inside that, add whatever results to your dataframe using the keys at
iandj.
All together:
keys = dict.keys()
for i in range(len(keys)):
for j in range(i + 1, len(keys)):
# add a new row to the dataframe using keys[i] and keys[j]
For the intuition, imagine taking a matrix of all dividing it in half diagonally, and then iterating through only the top half:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

