使用apply()将值赋给新列

2024-10-01 09:23:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个叫做sf的SFrame中有一个名为word_count的SArray。word_countSArray中的每一行都包含一个dict。 我有一个名为selected_words的数组 我试着在每一列中循环查看“所选单词”中的哪个单词出现在该列中。如果它出现了,我就取这个值并把它写到一个新的列中。 以下是一个单词(“great”)的示例:

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)被应用于每一行,但我只需要在真正找到单词“great”的那一行。 我该怎么做?在


Tags: andcountit数组sf单词dictword
1条回答
网友
1楼 · 发布于 2024-10-01 09:23:43

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

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

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

^{pr2}$

相关问题 更多 >