np.arange creates a null value matrix on resizing

Viewed 297

The following is the code that I am using:

import numpy as np
import pandas as pd
from pandas import DataFrame, Series
animals = DataFrame(np.arange(16).resize(4, 4), columns=['W', 'X', 'Y', 'Z'], index=['Dog', 'Cat', 'Bird', 'Mouse'])
print(animals)

The output I get for this is:

         W    X    Y    Z
Dog    NaN  NaN  NaN  NaN
Cat    NaN  NaN  NaN  NaN
Bird   NaN  NaN  NaN  NaN
Mouse  NaN  NaN  NaN  NaN

The output that I expect is:

         W    X    Y    Z
Dog      0    1    2    3
Cat      4    5    6    7
Bird     8    9   10   11
Mouse    12   13   14   15

However, if I run just:

print(np.arange(16))

the output I get is:

[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]
3 Answers

use reshape

import pandas as pd
animals = pd.DataFrame(np.arange(16).reshape(4, 4), columns=['W', 'X', 'Y', 'Z'], index=['Dog', 'Cat', 'Bird', 'Mouse'])
print(animals)

or use numpy.resize()

np.resize(np.arange(16),(4, 4))

using resize you need to pass the array as an argument

import pandas as pd
animals = pd.DataFrame(np.resize(np.arange(16),(4, 4)), columns=['W', 'X', 'Y', 'Z'], index=['Dog', 'Cat', 'Bird', 'Mouse'])
print(animals)

ndarray.resize() will do inplace operation. So precompute the size and then create a dataframe

a=np.arange(16)
a.resize(4,4)
import pandas as pd
animals = pd.DataFrame(a, columns=['W', 'X', 'Y', 'Z'], index=['Dog', 'Cat', 'Bird', 'Mouse'])
print(animals)

From the docs for resize: "Change shape and size of array in-place." Thus, your call to resize returns None.

You want reshape. As in np.arange(16).reshape(4, 4)

Just to add to the answer above, docs for resize:

ndarray.resize(new_shape, refcheck=True)

Change shape and size of array in-place.

Therefore, unlike reshape, resize doesn't create a new array. In fact np.arange(16).resize(4, 4) yields None, which is why you get the Nan values.

Using reshape returns a new array:

 ndarray.reshape(shape, order='C')

Returns an array containing the same data with a new shape

.

Related