首页 > 解决方案 > 在带参数的数据框中使用应用会返回错误

问题描述

我有以下代码

def mean_vectorizer(words, dimention, diction):
  return np.array([np.mean([diction[w] for w in words if w in diction] or [np.zeros(dimention)], axis=0)])

data['vector'] = data.apply(lambda x: mean_vectorizer(x['words'], 100, diction), axis=1)

数据框中的列words有一个单词列表。diction是一个以单词为键,以固定大小为值的数组的字典。我尝试做的是创建一个新列,它将解析每一行中的列表,从字典中获取每个单词的数组,并用其余的平均值计算一个数组。

运行上面的代码会返回这个错误:

Exception: Data must be 1-dimensional         

但是,如果我使用以下代码运行单行代码,它不会抱怨

words = data.iloc[0]['words']
np.array([np.mean([diction[w] for w in words if w in diction] or [np.zeros(dimention)], axis=0)])

标签: pythonpandas

解决方案


推荐阅读