首页 > 解决方案 > 我的 for 循环不起作用,我想知道发生了什么

问题描述

我的目标是编写一个可以多次运行的函数。输入是数据帧,输出也是数据帧。数据框是单列数据框。我要做的是每次从该列中提取 10 个单词并将其存储到一个新的数据框中。之后再次运行相同的函数,但这次取出第一个单词,然后从列中提取 10 个单词并将其放入我之前创建的数据框中。我正在测试 For 循环以查看它是否工作,但由于某种原因,for 循环不工作。它只运行 1 次而不是 3 次。我想知道我做错了什么吗?你们有更好的解决方案让我完成任务吗?

为了更好地理解,我将在下面简化我的任务。

  1. 从原始数据框(df)中提取 10 个单词
  2. 将它们存储到新的数据框(df1)中
  3. 再次运行该函数,但这次取出第一个单词然后进行提取。将它们存储/合并到 df1。
  4. 需要运行多次

所以输入数据框如下所示:

In [2]: df
Out [2]:  

   text
0 I love python and I want to learn more and more and more
1 I do not love python but I want to learn more and more and more
2 This function is not working and I do not know what to do about it
   :
   :
n This is the end of the dataframe and I hope you all understand

这是我尝试循环多次的代码:

def loop(dataframe):

    dataframe = df
   
    for i in range(3):
        
        df.loc[:,'text'] = df['text'].apply(lambda x: ' '.join(x.split()[:10]))

        df.loc[:,'text'] = df['text'].apply(lambda x: ' '.join(x.split(' ')[1:]))
        
        df1 = pd.DataFrame(df['text'])
       
        new = [df,df1]

        new_df = pd.concat(new)
      
    return new_df

我使用了 3 次作为文本值,但输出与我预期的不同。它表明我只跑了 1 次而不是 3 次。在进一步做任何事情之前,我试图先对此进行测试。

功能完全完成后,我希望看到如下内容:

   In [2]: loop(df)
   Out [2]: 
      text
    0 I love python and I want to learn more and more and more
    1 love python and I want to learn more and more and more
    2 python and I want to learn more and more and more
    3 I do not love python but I want to learn more and more and more
    4 do not love python but I want to learn more and more and more
    5 not love python but I want to learn more and more and more
    6 This function is not working and I do not know what to do about it
    7 function is not working and I do not know what to do about it
    8 is not working and I do not know what to do about it
       :
       :
    n the end of the dataframe and I hope you all understand

我很好奇我的代码做错了吗?或者你们对我这样做有什么其他建议吗?谢谢!!!

标签: pythonpandasdataframefor-loop

解决方案


推荐阅读