我有一个形状(X,Y)的Pandas数据帧对象,看起来如下:
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]以及形状(X,Z)的numpy稀疏矩阵(CSC),其形状如下所示
[[0, 1, 0],
[0, 0, 1],
[1, 0, 0]]如何在新的命名列中将矩阵中的内容添加到数据帧中,以便数据框架将以如下方式结束:
[[1, 2, 3, [0, 1, 0]],
[4, 5, 6, [0, 0, 1]],
[7, 8, 9, [1, 0, 0]]]注意,数据帧现在有了形状(X,Y+1),矩阵中的行是数据框架中的元素。
发布于 2013-09-05 21:29:40
import numpy as np
import pandas as pd
import scipy.sparse as sparse
df = pd.DataFrame(np.arange(1,10).reshape(3,3))
arr = sparse.coo_matrix(([1,1,1], ([0,1,2], [1,2,0])), shape=(3,3))
df['newcol'] = arr.toarray().tolist()
print(df)收益率
   0  1  2     newcol
0  1  2  3  [0, 1, 0]
1  4  5  6  [0, 0, 1]
2  7  8  9  [1, 0, 0]发布于 2013-09-05 22:13:48
考虑使用高维数据结构( 面板),而不是将数组存储在列中:
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看横截面等.
In [14]: p.xs(0)
Out[14]: 
   csc  df
0    0   1
1    1   2
2    0   3http://pandas.pydata.org/pandas-docs/stable/dsintro.html#panel。
发布于 2020-10-28 14:13:30
df = pd.DataFrame(np.arange(1,10).reshape(3,3))
df['newcol'] = pd.Series(your_2d_numpy_array)https://stackoverflow.com/questions/18646076
复制相似问题