Add numpy array as column to Pandas data frame

前端 未结 5 1354
离开以前
离开以前 2020-12-02 16:30

I have a Pandas data frame object of shape (X,Y) that looks like this:

[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]

and a numpy sparse matrix (CSC) of

5条回答
  •  执念已碎
    2020-12-02 16:57

    Consider using a higher dimensional datastructure (a Panel), rather than storing an array in your column:

    In [11]: p = pd.Panel({'df': df, 'csc': csc})
    
    In [12]: p.df
    Out[12]: 
       0  1  2
    0  1  2  3
    1  4  5  6
    2  7  8  9
    
    In [13]: p.csc
    Out[13]: 
       0  1  2
    0  0  1  0
    1  0  0  1
    2  1  0  0
    

    Look at cross-sections etc, etc, etc.

    In [14]: p.xs(0)
    Out[14]: 
       csc  df
    0    0   1
    1    1   2
    2    0   3
    

    See the docs for more on Panels.

提交回复
热议问题