【发布时间】:2019-06-05 00:10:59
【问题描述】:
背景
1) 我有以下代码来创建df
import pandas as pd
word_list = ['crayons', 'cars', 'camels']
l = ['there are many different crayons in the bright blue box',
'i like a lot of sports cars because they go really fast',
'the middle east has many camels to ride and have fun']
df = pd.DataFrame(l, columns=['Text'])
df
Text
0 there are many different crayons in the bright blue box
1 i like a lot of sports cars because they go really fast
2 the middle east has many camels to ride and have fun
2)我有以下代码来创建一个函数
def find_next_words(row, word_list):
sentence = row[0]
# trigger words are the elements in the word_list
trigger_words = []
next_words = []
last_words = []
for keyword in word_list:
words = sentence.split()
for index in range(0, len(words) - 1):
if words[index] == keyword:
trigger_words.append(keyword)
#get the 3 words that follow trigger word
next_words.append(words[index + 1:index + 4])
#get the 3 words that come before trigger word
#DOES NOT WORK...PRODUCES EMPTY LIST
last_words.append(words[index - 1:index - 4])
return pd.Series([trigger_words, last_words, next_words], index = ['TriggerWords','LastWords', 'NextWords'])
3) 此函数使用上面word_list 中的单词来查找word_list 中before 和after "trigger_words" 的3 个单词
4) 然后我使用下面的代码
df = df.join(df.apply(lambda x: find_next_words(x, word_list), axis=1))
5) 它会产生以下df,这与我想要的很接近
Text TriggerWords LastWords NextWords
0 there are many different crayons [crayons] [[]] [[in, the, bright]]
1 i like a lot of sports cars [cars] [[]] [[because, they, go]]
2 the middle east has many camels [camels] [[]] [[to, ride, and]]
问题
6) 但是,LastWords 列是列表 [[]] 的空列表。我认为问题在于这行代码last_words.append(words[index - 1:index - 4]) 取自上面的find_next_words 函数。
7) 这让我有点困惑,因为 NextWords 列使用了非常相似的代码 next_words.append(words[index + 1:index + 4]),取自 find_next_words 函数并且它有效。
问题
8) 如何修复我的代码,使其不会生成空列表 [[]],而是为我提供 word_list 中单词之前的 3 个单词?
【问题讨论】:
标签: python-3.x pandas function loops dataframe