【问题标题】:pandas dataframe to coo matrix and to lil matix熊猫数据框到 coo 矩阵和 lil matix
【发布时间】:2020-01-09 21:56:10
【问题描述】:

我有以下系列:

groups['combined'] 

0            (28, 1)  1
1           (32, 1)  1
2           (36, 1)  1
3           (37, 1)  1
4           (84, 1)  1

....
Name: combined, Length: 14476, dtype: object

如何将此数据帧转换为.tocoo() 矩阵和.tolil()

参考combined 列是如何形成的 原始 Pandas 数据框:

import pandas as pdpd.DataFrame({0:[28,32,36,37,84],1: [1,1,1,1,1], 2: [1,1,1,1,1]})。 col 0 有超过 10K 的独特功能,col 1 有 39 个组,col 2 只有 1 个。

【问题讨论】:

  • 您阅读过sparse.coo_matrix 文档吗?
  • 一点点,但没有意义
  • 该系列的元素(单元格)是什么?字符串?它们看起来像一个 coo 矩阵的显示
  • @hpaulj - 这些是来自 pandas 数据框列的构造: pd.DataFrame({0:[28,32,36,37,84],1: [1,1,1,1 ,1], 2: [1,1,1,1,1]}),列 '1' 有 39 个唯一元素。 '0' 列有 10K。 'combined' 是三列的连接 - 包含 col 0 和 col 1 的元组。
  • 我怀疑原始数据框列比组合更有用。它们看起来像可以用作row, coldata 参数到coo_matrix 的数组。

标签: pandas numpy scipy sparse-matrix


【解决方案1】:

Formation of COOrdinate format from original pandas DataFrame

    import scipy.sparse as sps

    groups.set_index([0, 1], inplace=True)
    sps.coo_matrix((groups[2], (groups.index.labels[0], groups.index.labels[1])))

-------------结果---------

<10312x39 sparse matrix of type '<class 'numpy.int64'>'
    with 14476 stored elements in COOrdinate format>

【讨论】:

  • 这就是我所期望的。该矩阵的print 看起来很像您最初显示的(i,j) d 列 - 但具有更多值。
  • 拥有coo 格式后,您可以使用tolil() 制作lil 格式。但是你需要吗? coo 非常适合像您所做的那样构建矩阵。 lil 用于一一填写值,但我认为您不需要。 csr 用于大多数计算。
  • 我正在处理图形数据,所以需要lil。有没有更好的办法?
  • 为什么要有更好的方法?您的来源自然会提供coo 格式。开发人员试图做好转换器的编写工作。使用它们。
【解决方案2】:

In regards to lil matrix

print(len(networks[0]), len(networks[1]), networks[0].nunique(), networks[1].nunique())
667966 667966 10312 10312
networks[:5]

    0   1
0   176 1
1   233 1
2   283 1
3   371 1
4   394 1


# make row and col labels
rows = networks[0]
cols = networks[1]

# crucial third array in python
networks.set_index([0, 1], inplace=True)
Ntw= sps.coo_matrix((networks[2], (networks.index.labels[0], 
networks.index.labels[1])))


d=Ntw.tolil()
d

生成

   <10312x10312 sparse matrix of type '<class 'numpy.int64'>'
    with 667966 stored elements in LInked List format>

【讨论】:

  • d 的形状应与ones 相同
  • 我打赌 networks[0]networks[1] 不是零索引,但 coo_matrix 将永远是
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-10
  • 2017-04-11
  • 2021-10-02
  • 1970-01-01
  • 2020-12-15
  • 2019-07-09
  • 2018-01-25
相关资源
最近更新 更多