将numpy数组作为列添加到Pandas数据框 [英] Add numpy array as column to Pandas data frame
本文介绍了将numpy数组作为列添加到Pandas数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个形状为(X,Y)的Pandas数据框对象,如下所示:
I have a Pandas data frame object of shape (X,Y) that looks like this:
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
和形状为(X,Z)的Numpy稀疏矩阵(CSC)看起来像这样
and a numpy sparse matrix (CSC) of shape (X,Z) that looks something like this
[[0, 1, 0],
[0, 0, 1],
[1, 0, 0]]
如何将矩阵中的内容添加到新命名列中的数据框中,以使数据框最终像这样:
How can I add the content from the matrix to the data frame in a new named column such that the data frame will end up like this:
[[1, 2, 3, [0, 1, 0]],
[4, 5, 6, [0, 0, 1]],
[7, 8, 9, [1, 0, 0]]]
请注意,数据框现在具有形状(X,Y + 1),并且矩阵中的行是数据框中的元素.
Notice the data frame now has shape (X, Y+1) and rows from the matrix are elements in the data frame.
推荐答案
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]
这篇关于将numpy数组作为列添加到Pandas数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文