0

我在 mysql 中有这个表,其中我有每个不同 ID 的每个 ITEM 的出现次数(CNT 列):

ID     ITEM      CNT
---------------------
01     093        4
01     129F       2
01     AB56       0
01     BB44       0
01     XH7        0
01     TYE2       1
02     093        0
02     129F       3
02     AB56       1
02     BB44       0
02     XH7        2
02     TYE2       2
03     093        9
03     129F       2
03     AB56       0
03     BB44       1
03     XH7        4
03     TYE2       0
......

我想找到一种将这些数据从 MySQL 导入 Python 的有效方法,以便我可以将它们用作聚类过程的项目计数向量,以列表列表的形式:

[[4,2,0,0,0,1],[0,3,1,0,2,2],[9,2,0,1,4,0]]

每个列表代表一个 ID ...我正在处理大量数据(数百万行),因此性能是一个问题。任何帮助将不胜感激

4

1 回答 1

1

使用itertools.groupby

...
cursor.execute('SELECT ID, CNT FROM table_name ORDER BY ID')
item_count_vector = [
    [cnt for id_, cnt in grp]
    for key, grp in itertools.groupby(cursor.fetchall(), key=lambda row: row[0])
]

或(如果您使用DictCursor-like 光标)

item_count_vector = [
    [d['CNT'] for d in grp]
    for key, grp in itertools.groupby(cursor.fetchall(), key=lambda row: row['ID'])
]

...

>>> import itertools
>>> # Assume following rows are retrieved from DB using cursor.fetchall()
>>> rows = (
...     ('01',4),
...     ('01',2),
...     ('01',0),
...     ('01',0),
...     ('01',0),
...     ('01',1),
...     ('02',0),
...     ('02',3),
...     ('02',1),
...     ('02',0),
...     ('02',2),
...     ('02',2),
...     ('03',9),
...     ('03',2),
...     ('03',0),
...     ('03',1),
...     ('03',4),
...     ('03',0),
... )
>>> [[cnt for id_, cnt in grp] for key, grp in itertools.groupby(rows, key=lambda row: row[0])]
[[4, 2, 0, 0, 0, 1], [0, 3, 1, 0, 2, 2], [9, 2, 0, 1, 4, 0]]
于 2013-08-05T14:29:21.220 回答