【发布时间】:2019-12-03 12:39:05
【问题描述】:
我想以 矢量化 方式从数据框创建一个 备用矩阵,其中包含一个 标签矢量 和一个 矢量的值,同时知道所有标签。
另一个限制是,我不能先创建密集数据帧,然后将其转换为备用数据帧,因为它太大而无法保存在内存中。
示例:
所有可能的标签列表:
all_labels = ['a','b','c','d','e',\
'f','g','h','i','j',\
'k','l','m','n','o',\
'p','q','r','s','t',\
'u','v','w','z']
每行带有特定标签值的数据框:
data = {'labels': [['b','a'],['q'],['n','j','v']],
'scores': [[0.1,0.2],[0.7],[0.3,0.5,0.1]]}
df = pd.DataFrame(data)
预期的密集输出:
这就是我以非矢量化的方式完成的,这花费了太多时间:
from scipy import sparse
from scipy.sparse import coo_matrix
def labels_to_sparse(input_):
all_, lables_, scores_ = input_
rows = [0]*len(all_)
cols = range(len(all_))
vals = [0]*len(all_)
for i in range(len(lables_)):
vals[all_.index(lables_[i])] = scores_[i]
return coo_matrix((vals, (rows, cols)))
df['sparse_row'] = df.apply(
lambda x: labels_to_sparse((all_labels, x['labels'], x['scores'])), axis=1
)
df
尽管这可行,但由于必须使用df.apply,因此在处理较大数据时速度非常慢。有没有办法对这个函数进行矢量化,以避免使用apply?
最后,我想用这个数据框来创建矩阵:
my_result = sparse.vstack(df['sparse_row'].values)
my_result.todense() #not really needed - just for visualization
编辑
总结公认的解决方案(@Divakar 提供):
all_labels = np.sort(all_labels)
n = len(df)
lens = list(map(len,df['labels']))
l_ar = np.concatenate(df['labels'].to_list())
d = np.concatenate(df['scores'].to_list())
R = np.repeat(np.arange(n),lens)
C = np.searchsorted(all_labels,l_ar)
my_result = coo_matrix( (d, (R, C)), shape = (n,len(all_labels)))
【问题讨论】:
标签: python pandas vectorization sparse-matrix