python - 我的 for 循环不起作用,我想知道发生了什么
问题描述
我的目标是编写一个可以多次运行的函数。输入是数据帧,输出也是数据帧。数据框是单列数据框。我要做的是每次从该列中提取 10 个单词并将其存储到一个新的数据框中。之后再次运行相同的函数,但这次取出第一个单词,然后从列中提取 10 个单词并将其放入我之前创建的数据框中。我正在测试 For 循环以查看它是否工作,但由于某种原因,for 循环不工作。它只运行 1 次而不是 3 次。我想知道我做错了什么吗?你们有更好的解决方案让我完成任务吗?
为了更好地理解,我将在下面简化我的任务。
- 从原始数据框(df)中提取 10 个单词
- 将它们存储到新的数据框(df1)中
- 再次运行该函数,但这次取出第一个单词然后进行提取。将它们存储/合并到 df1。
- 需要运行多次
所以输入数据框如下所示:
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
我很好奇我的代码做错了吗?或者你们对我这样做有什么其他建议吗?谢谢!!!
解决方案
推荐阅读
- java - java泛型类中的double方法
- azure - 占位符 URL 与 Azure Blob 存储
- swift - 使用提供 nsurlsession 的 rapidapi 访问 json
- windows - 当我在 Windows 10 上的 git bash 中运行 git-gui 时,我得到“第 3 行:执行:希望:未找到”
- excel - 通过 XML 文件解析 Excel VBA objDOM 不起作用
- discord.js - Discord.Js 在线状态更新循环修复
- java - Spring Data JPA saveAll 不进行批量插入
- python - 有效地将表示浮点数列表的字符串解析为字符串列表
- python - Python 无法从 dict 写入数据帧。简单的
- asp.net - 我是 .NET Core 2.1 MVC 的新手,我无法理解一些事情是如何工作的