0

word_count我有一个SFrame名为 sf的 SArray 。word_countSArray中的每一行都由一个字典组成。我有一个名为的数组,selected_words 我试图遍历每一列,以查看“selected_words”中的哪些单词出现在该列中。如果出现,我将取值并将其写入新列。这是一个仅包含一个词(“很棒”)的示例:

selected_words = ['awesome ', 'great']
def word_count(row):
    if 'great' in row:
           sf['great']=row['great']
    else:
         abc="a" #nothing should happen
sf['word_count'].apply(word_count)

+-------------------------------+
|           word_count          |
+-------------------------------+
| {'and': 5, '6': 1, 'stink'... |
| {'and': 3, 'love': 1, 'it'... |
| {'and': 2, 'quilt': 1, 'it... |
| {'ingenious': 1, 'and': 3,... |
| {'and': 2, 'parents!!': 1,... |
| {'and': 2, 'this': 2, 'her... |
| {'shop': 1, 'noble': 1, 'i... |
| {'and': 2, 'all': 1, 'righ... |
| {'and': 1, 'help': 1, 'giv... |
| {'journal.': 1, 'nanny': 1... |
+-------------------------------+


print sf['great']
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ... ]

据我了解,相同的值(1)应用于每一行,但我只需要在实际找到“伟大”一词的那一行中使用它。我怎样才能做到这一点?

4

1 回答 1

2

您的代码中的问题是您在每次调用函数 word_count 后都更改了整列 sf['great']。这是另一种方法:

def word_count(d):
    return d['great'] if 'great' in d else 0

然后将此函数应用于 sf['word_count'] 列:

sf['great'] = sf['word_count'].apply(word_count)
于 2015-11-01T12:03:58.350 回答