从MySQL表到Python列表

时间:2013-08-05 14:23:25

标签: python mysql database

我在mysql中有这个表,我在每个ITEM的每个不同ID的出现(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 ...... 我正在处理大量数据(数百万行),因此性能是个问题。 任何帮助将不胜感激

1 个答案:

答案 0 :(得分: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])
]

OR(如果您使用DictCursor - 像游标一样)

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]]