is there numpy.asarray like function in pandas?

I wanna convert a nd array or some columns to pandas temporarily to use its functionality, so I do not wanna copy data, I wanna only copy view like numpy.asarray.

1 answer

  • answered 2018-03-21 01:36 user2699

    According to the documentation (https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html), you can pass copy=False in the constructor. That's already the default argument, so you shouldn't need to do anything.

    This follows the behavior of numpy arrays (well, the default argument is True for numpy rather than False. Pandas can't be that consistent), and in fact the definition for asarray uses this same approach:

    def asarray(a, dtype=None, order=None):
        """Convert the input to an array...
        """
        return array(a, dtype, copy=False, order=order)
    

    Numpy documentation states that

    copy : bool, optional If true (default), then the object is copied. Otherwise, a copy will only be made if array returns a copy, if obj is a nested sequence, or if a copy is needed to satisfy any of the other requirements (dtype, order, etc.).

    And despite pandas stating

    copy : boolean, default False Copy data from inputs. Only affects DataFrame / 2d ndarray input

    it will affect the behavior of 1d arrays, and will copy if the dtype argument does not match the underlying data.

    An example:

    In [10]: t = np.arange(10)
    
    In [11]: p = pd.DataFrame(t)
    
    In [12]: t
    Out[12]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
    
    In [13]: p
    Out[13]: 
       0
    0  0
    1  1
    2  2
    3  3
    4  4
    5  5
    6  6
    7  7
    8  8
    9  9
    
    In [14]: t[:3] = 4
    
    In [15]: t
    Out[15]: array([4, 4, 4, 3, 4, 5, 6, 7, 8, 9])
    
    In [16]: p
    Out[16]: 
       0
    0  4
    1  4
    2  4
    3  3
    4  4
    5  5
    6  6
    7  7
    8  8
    9  9