不产生熊猫的空列表

时间:2019-06-05 00:10:59

标签: python-3.x pandas function loops dataframe

背景

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中的单词来查找位于"trigger_words"中的之前之后的3个单词word_list

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个单词?

1 个答案:

答案 0 :(得分:0)

我认为代码中应为words[max(index - 4, 0):max(index - 1, 0)]

相关问题