从项目集到数据框的python pandas [英] python pandas from itemset to dataframe

查看:43
本文介绍了从项目集到数据框的python pandas 的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从项目集列表中获取更具扩展性的方法是什么:

What is the more scalable way to go from an itemset list::

itemset = [['a', 'b'],
           ['b', 'c', 'd'],
           ['a', 'c', 'd', 'e'],
           ['d'],
           ['a', 'b', 'c'],
           ['a', 'b', 'c', 'd']]

对于这种数据框::

>>> df
   a  b  c  d  e
0  1  1  0  0  0
1  0  1  1  1  0
2  1  0  1  1  1
3  0  0  0  1  0
4  1  1  1  0  0
5  1  1  1  1  0
>>>

df的目标大小为1e6行500列.

The target size of df is 1e6 rows and 500 columns.

推荐答案

这是一种几乎矢量化的方法-

Here's an almost vectorized approach -

items = np.concatenate(itemset)           
col_idx = np.fromstring(items, dtype=np.uint8)-97

lens = np.array([len(item) for item in itemset])
row_idx = np.repeat(np.arange(lens.size),lens)
out = np.zeros((lens.size,lens.max()+1),dtype=int)
out[row_idx,col_idx] = 1   

df = pd.DataFrame(out,columns=np.unique(items))

最后一行可以用类似的内容代替,并且性能更高-

The last line could be replaced by something like this and could be more performant -

df = pd.DataFrame(out,columns=items[np.unique(col_idx,return_index=True)[1]])

这篇关于从项目集到数据框的python pandas 的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆