我有一个形状为(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),矩阵中的行是数据框中的元素。
5条答案
按热度按时间33qvvth11#
字符串
产量
型
ih99xse12#
字符串
np8igboo3#
考虑使用更高维的数据结构(Panel),而不是在列中存储数组:
字符串
看看横截面等等。
型
zfycwa2u4#
你可以使用以下命令从dataframe中添加和检索一个numpy数组:
字符串
这是建立在之前的答案上的,因为稀疏部分让我感到困惑,这对于非稀疏numpy数组很有效。
kcwpcxri5#
下面是另一个例子:
字符串
一般来说,秘密是以a = [(array_11,array_12,...,array_1n),...,(array_m1,array_m2,.,array_mn)]的形式分配数据,而panda DataFrame会将数据排序在n列数组中。当然,可以使用数组的数组来代替元组,在这种情况下,形式将是:a = [ [array_11,array_12,.,array_1n],...,[array_m1,array_m2,.,array_mn] ]
这是从上面的代码打印(df)的输出:
型
以上示例的其他变型:
型
df输出:
型
如果要添加数组的其他列,则:
型
df的最终输出将是:
型