字符串熊猫系列到字符串变量



一直在寻找从数据框中的字符串列中获取字符串变量的方法。在最基本的场景中,我有一个名为 name 的字符串变量,该变量基于空间进行填充以获取字符串列表(在名为 names 的示例中(。然后,将列表作为参数发送到函数以处理列表的每个元素:

name = "4 PAWS ONLY"
type(name) #String type
names= name.split()
type(names) #list type
print(names) #['4', 'PAWS', 'ONLY']
#avg_vector needs a list of string, called names
avg_vector = avg_sentence_vector(names, model=word2vec_model, num_features=300, index2word_set=set(word2vec_model.wv.index2word)).tolist()

在此基本方案中,avg_sentence_vector执行时没有错误,因为参数满足函数输入。

在理想情况下,相同的逻辑适用,但适用于数据帧的每一行。字符串来自名为"name"的列(而不是字符串变量(,该列需要以与前面的示例相同的方式进行填充,并将列表传递给函数。

到目前为止,从"name"列中拆分字符串值后,我无法获得字符串列表:

names = ['4 PAWS ONLY']
df = pd.DataFrame(data=None, index=range(1), columns=['names', 'avg_vector'])
df['names'] = names
vname = df.names.apply(str)
type(vname) #pandas.core.series.Series
vnames = vname.str.split()
type(vnames) #pandas.core.series.Series
print(vname)
0    [4, PAWS, ONLY]
Name: names, dtype: object
#avg_vector needs a list of string, called vnames
avg_vector = avg_sentence_vector(vnames, model=word2vec_model, num_features=300, index2word_set=set(word2vec_model.wv.index2word)).tolist()

函数的执行显示以下错误:

<ipython-input-9-2abbbce044f5> in avg_sentence_vector(words, model, num_features, index2word_set)
---> 11         if word in index2word_set:
12             nwords = nwords+1
13             featureVec = np.add(featureVec, model[word])
TypeError: unhashable type: 'list'

函数avg_sentence_vector的主体如下:

##Get average sentence vector
def avg_sentence_vector(words, model, num_features, index2word_set):
#function to average all words vectors in a given paragraph
featureVec = np.zeros((num_features,), dtype="float32")
nwords = 0
for word in words:
print(word)
print(index2word_set)
if word in index2word_set:
nwords = nwords+1
featureVec = np.add(featureVec, model[word])
if nwords>0:
featureVec = np.divide(featureVec, nwords)
return featureVec

如何从数据帧字符串列传递字符串列表?是否有其他可能的失败原因?

谢谢

您可以通过以下方式使用 apply 来执行此操作:

def avg_sentence_vector(ll, *args, **kwargs):
return len(ll)
df['avg_vector'] = df.apply(lambda row : avg_sentence_vector(row['names'].split()), axis=1)

这将返回:

names  avg_vector
0  4 PAWS ONLY           3

如您所见,在我的例子中,avg_sentence_vector函数返回传递列表的长度,但当然它可以是任何东西。您也可以传递所需的所有额外参数。

评论后编辑

注意不要将函数的参数与apply参数(如axis(混合。如果你的函数接受多个参数,你需要做:

df['avg_vector'] = df.apply(lambda row : avg_sentence_vector(row['names'].split(), model=word2vec_model, num_features=300, ...), axis=1)

其中...代表函数可能需要的任何其他参数。所有这些都需要在avg_sentence_vector的括号内,轴=1必须是最后一个。

最新更新