Asked  10 Months ago    Answers:  5   Viewed   4 times

When I check the shape of an array using numpy.shape(), I sometimes get (length,1) and sometimes (length,). It looks like the difference is a column vs. row vector... but It doesn't seem like that changes anything about the array itself [except some functions complain when I pass an array with shape (length,1)].

What is the difference between these two?
Why isn't the shape just, (length)?

 Answers

5

The point is that say a vector can be seen either as

  • a vector
  • a matrix with only one column
  • a 3 dimensional array where the 2nd and 3rd dimensions have length one
  • ...

You can add dimensions using [:, np.newaxis] syntax or drop dimensions using np.squeeze:

>>> xs = np.array([1, 2, 3, 4, 5])
>>> xs.shape
(5,)
>>> xs[:, np.newaxis].shape  # a matrix with only one column
(5, 1)
>>> xs[np.newaxis, :].shape  # a matrix with only one row
(1, 5)
>>> xs[:, np.newaxis, np.newaxis].shape  # a 3 dimensional array
(5, 1, 1)
>>> np.squeeze(xs[:, np.newaxis, np.newaxis]).shape
(5,)
Wednesday, August 11, 2021
 
3
header('content-type:text/plain');

$arr = array(
    'a' => array(
        'b' => array(
            'c' => 'hello',
        ),
    ),
    'd' => array(
        'e' => array(
            'f' => 'world',
        ),
    ),
);

//prime the stack using our format
$stack = array();
foreach ($arr as $k => &$v) {
    $stack[] = array(
        'keyPath' => array($k),
        'node' => &$v
    );
}

$lookup = array();

while ($stack) {
    $frame = array_pop($stack);
    $lookup[join('/', $frame['keyPath'])] = &$frame['node'];
    if (is_array($frame['node'])) {
        foreach ($frame['node'] as $key => &$node) {
            $keyPath = array_merge($frame['keyPath'], array($key));
            $stack[] = array(
                'keyPath' => $keyPath,
                'node' => &$node
            );
            $lookup[join('/', $keyPath)] = &$node;
        }
    }
}


var_dump($lookup);
// check functionality
$lookup['a'] = 0;
$lookup['d/e/f'] = 1;
var_dump($arr);

Alternatively you could have done stuff like this to get a reference /w array_pop functionality

end($stack);
$k = key($stack);
$v = &$stack[$k];
unset($stack[$k]);

That works because php arrays have elements ordered by key creation time. unset() deletes the key, and thus resets the creation time for that key.

Thursday, April 1, 2021
 
3

Problem is you're using numpy.math.cos here, which expects you to pass a scalar. Use numpy.cos if you want to apply cos to an iterable.

In [30]: import numpy as np

In [31]: np.cos(np.array([1, 2, 3]))                                                             
Out[31]: array([ 0.54030231, -0.41614684, -0.9899925 ])

Error:

In [32]: np.math.cos(np.array([1, 2, 3]))                                                        
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-32-8ce0f3c0df04> in <module>()
----> 1 np.math.cos(np.array([1, 2, 3]))

TypeError: only length-1 arrays can be converted to Python scalars
Wednesday, August 18, 2021
 
Akdeniz
 
1
In [42]: some_df = pd.DataFrame(columns=['A']) 
    ...: for i in range(4): 
    ...:         some_df.loc[i] = [np.random.randint(0,10,(1,3))] 
    ...:                                                                                  
In [43]: some_df                                                                          
Out[43]: 
             A
0  [[7, 0, 9]]
1  [[3, 6, 8]]
2  [[9, 7, 6]]
3  [[1, 6, 3]]

The numpy values of the column are an object dtype array, containing arrays:

In [44]: some_df['A'].to_numpy()                                                          
Out[44]: 
array([array([[7, 0, 9]]), array([[3, 6, 8]]), array([[9, 7, 6]]),
       array([[1, 6, 3]])], dtype=object)

If those arrays all have the same shape, stack does a nice job of concatenating them on a new dimension:

In [45]: np.stack(some_df['A'].to_numpy())                                                
Out[45]: 
array([[[7, 0, 9]],

       [[3, 6, 8]],

       [[9, 7, 6]],

       [[1, 6, 3]]])
In [46]: _.shape                                                                          
Out[46]: (4, 1, 3)

This only works with one column. stack like all concatenate treats the input argument as an iterable, effectively a list of arrays.

In [48]: some_df['A'].to_list()                                                           
Out[48]: 
[array([[7, 0, 9]]),
 array([[3, 6, 8]]),
 array([[9, 7, 6]]),
 array([[1, 6, 3]])]
In [50]: np.stack(some_df['A'].to_list()).shape                                           
Out[50]: (4, 1, 3)
Thursday, September 2, 2021
 
danjah
 
5

To take an input:

def chunks(l, n):
    return [l[i:i+n] for i in range(0, len(l), n)]

mylist = [1,2,3,4,5,6,7,8]
while 1:
    try:
        size = int(raw_input('What size? ')) # Or input() if python 3.x
        break
    except ValueError:
        print "Numbers only please"

print chunks(yourlist, size)

Prints:

[[1, 2], [3, 4], [5, 6], [7, 8]] # Assuming 2 was the input

Or even:

>>> zip(*[iter(l)]*size) # Assuming 2 was the input
[(1, 2), (3, 4), (5, 6), (7, 8)]
Thursday, October 21, 2021
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share