I have an issue with some part of my code, I’m fetching two apis and then mixing the results in one array:
Initialy the two arrays seems like this (although they can be empty or with more or less data):
JavaScript
x
10
10
1
print(foo)
2
[[0, 0, 1, 2, 2, 2, 2, 2, 1, 2, 2, 2, 0, 2, 2, 2, 1, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 0, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 0, 2, 0, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 1, 0, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 1, 0, 2, 2, 2, 1, 1], [0, 0, 1, 2, 2, 2, 2, 2, 1, 2, 2, 2, 0, 2, 2, 2, 1, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 0, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2 , 2, 2, 1, 2, 0, 2, 0, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 1, 0, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 1, 0, 2, 2, 2, 1, 1], [0, 0, 1, 2, 2, 2, 2, 2, 1, 2, 2, 2, 0, 2, 2, 2, 1, 2, 2,
3
2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 0, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 0, 2, 0, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 1, 0, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 1, 0, 2, 2, 2, 1, 1], [0, 0, 1, 2, 2, 2, 2, 2, 1, 2, 2, 2, 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 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 0, 2, 0, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 1, 0, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 1, 0, 2, 2, 2]]
6
7
print(bar)
8
[[1, 1, 1, 2, 2, 1, 2, 1, 0, 1, 1, 1, 1, 1], [1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 2, 2, 0, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 2, 1, 2, 1, 1, 1, 1, 0, 2, 2], [1, 0, 0, 0, 1, 2, 1, 2, 2, 2, 1, 1, 2, 0, 1, 1, 0, 0, 1, 1], [2, 0,
9
2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1], [2, 1, 1, 1, 2, 2, 2, 1, 2, 1, 2, 1, 1, 2, 1, 2, 1, 1, 2, 1], [1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 2]]
10
Their shapes are:
JavaScript
1
5
1
foo --> (7,) (the 2nd dimension varies on shape so numpy doesn't get it)
2
bar --> (7, 20) (In this case the sublists len() matches, but maybe won't in the future)
3
[len(i) for i in foo] --> [94, 95, 96, 96, 97, 96, 95] # not all sublists are equal in length
4
[len(i) for i in bar] --> [20, 20, 20, 20, 20, 20, 20]
5
So of course, when I try to append them in the 2nd dimension:
JavaScript
1
2
1
df = np.hstack([foo, bar]).tolist()
2
I get this error:
JavaScript
1
2
1
ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 2 dimension(s) and the array at index 1 has 1 dimension(s)
2
My question is what would be the best solution to this, trying to not loose data, maybe appending each sublist manually work but is it the only solution I have?
Advertisement
Answer
One array only has 1 dimension, the other has 2. But you can quickly adjust the first array to have dimensions (7,1) by using newaxis
For example:
JavaScript
1
2
1
df = np.hstack([foo[:, np.newaxis], bar]).tolist()
2