Jeff
Jeff

Reputation: 8411

Python: How to convert whole array into int

I wish to have an int matrix which has only its first column filled and the rest of elements are Null. Sorry but, I have a background of R. So, I know if I leave some Null elements it would be easier to manage them later. Meanwhile, if I leave 0 then it would be lots of problems later.

I have the following code:

   import numpy as np
   import numpy.random as random
   import pandas as pa

    def getRowData():
        rowDt = np.full((80,20), np.nan)
        rowDt[:,0] =  random.choice([1,2,3],80) # Set the first column
        return  rowDt

I wish that this function returns the int, but seems that it gives me float.

I have seen this link, and tried the below code:

return  pa.to_numeric(rowDt)

But, it did not help me. Also the rowDT object does not have .astype(<type>).

How can I convert an int array?

Upvotes: 0

Views: 640

Answers (2)

fountainhead
fountainhead

Reputation: 3722

You can use numpy.ma.masked_array() to create a numpy masked array

The numpy masked array "remembers" which elements are "masked". It provides methods and functions similar to those of numpy arrays, but excluding the masked values from the computations (such as, eg, mean()).

Once you have the masked array, you can always mask or unmask specific elements or rows or columns of elements whenever you want.

Upvotes: 0

rafaelc
rafaelc

Reputation: 59264

You create a full (np.full ) matrix of np.nan, which holds float dtype. This means you start off with a matrix defined to hold float numbers, not integers.

To fix this, fefine a full matrix with the integer 0 as initial value. That way, the dtype of your array is np.int and there is no need for astype or type casting.

rowDt = np.full((80,20), 0)

If you still wish to hold np.nan in your matrix, then I'm afraid you cannot use numpy arrays for that. You either hold all integers, or all floats.

Upvotes: 1

Related Questions