Put a 2d Array into a Pandas Series

前端 未结 2 2106
故里飘歌
故里飘歌 2021-02-12 18:07

I have a 2D Numpy array that I would like to put in a pandas Series (not a DataFrame):

>>> import pandas as pd
>>> import numpy as np
>>&         


        
2条回答
  •  我在风中等你
    2021-02-12 18:55

    Well, you can use the numpy.ndarray.tolist function, like so:

    >>> a = np.zeros((5,2))
    >>> a
    array([[ 0.,  0.],
           [ 0.,  0.],
           [ 0.,  0.],
           [ 0.,  0.],
           [ 0.,  0.]])
    >>> a.tolist()
    [[0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0]]
    >>> pd.Series(a.tolist())
    0    [0.0, 0.0]
    1    [0.0, 0.0]
    2    [0.0, 0.0]
    3    [0.0, 0.0]
    4    [0.0, 0.0]
    dtype: object
    

    EDIT:

    A faster way to accomplish a similar result is to simply do pd.Series(list(a)). This will make a Series of numpy arrays instead of Python lists, so should be faster than a.tolist which returns a list of Python lists.

提交回复
热议问题