Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用pandas将句子分成包含不同数量单词的子字符串_Python_String_Pandas_Tokenize - Fatal编程技术网

Python 使用pandas将句子分成包含不同数量单词的子字符串

Python 使用pandas将句子分成包含不同数量单词的子字符串,python,string,pandas,tokenize,Python,String,Pandas,Tokenize,我的问题与我过去的问题有关: 假设我在pandas中的DataFrame中有以下内容: id text 1 I am the first document and I am very happy. 2 Here is the second document and it likes playing tennis. 3 This is the third document and it looks very good today. 我想将每个id的文本拆分为随机单词数(在两个值之间

我的问题与我过去的问题有关:

假设我在
pandas
中的
DataFrame
中有以下内容:

id  text
1   I am the first document and I am very happy.
2   Here is the second document and it likes playing tennis.
3   This is the third document and it looks very good today.
我想将每个id的文本拆分为随机单词数(在两个值之间变化,例如1和5)的标记,因此我最终希望得到如下内容:

id  text
1   I am the
1   first document
1   and I am very
1   happy
2   Here is
2   the second document and it
2   likes playing
2   tennis
3   This is the third
3   document and
3   looks very
3   very good today
请记住,除了这两列之外,我的数据帧可能还有其他列,这两列应该以与上面的
id
相同的方式简单地复制到新的数据帧


最有效的方法是什么?

定义一个函数,使用
itertools.islice以随机方式提取块:

from itertools import islice
import random

lo, hi = 3, 5 # change this to whatever
def extract_chunks(it):
    chunks = []
    while True:
        chunk = list(islice(it, random.choice(range(lo, hi+1))))
        if not chunk:
            break
        chunks.append(' '.join(chunk))

    return chunks
通过列表理解调用函数以确保尽可能减少开销,然后
stack
获取输出:

pd.DataFrame([
    extract_chunks(iter(text.split())) for text in df['text']], index=df['id']
).stack()

id   
1   0                    I am the
    1        first document and I
    2              am very happy.
2   0                 Here is the
    1         second document and
    2    it likes playing tennis.
3   0           This is the third
    1       document and it looks
    2            very good today.
您可以扩展
extract_chunks
函数来执行标记化。现在,我使用一个简单的空格拆分,您可以修改它


请注意,如果您不想触摸其他列,可以在此处执行类似于
melt
ing操作的操作

u = pd.DataFrame([
    extract_chunks(iter(text.split())) for text in df['text']])

(pd.concat([df.drop('text', 1), u], axis=1)
   .melt(df.columns.difference(['text'])))

谢谢,看起来很有趣:)(向上投票)。顺便说一句,我希望最终的输出是一个带有索引重置和两列的公共数据框:id和文本-无多索引等。为了完整性起见,您可以对其进行修复。@PoeemAudit add.reset\u index(level=1,name=“text”,drop=True)顺便问一下,您确定我最后一个问题的答案吗?我认为答案是
。重置索引(level=1,drop=True)。重置索引(name=“text”)
。您的答案返回的序列没有
文本
标题。@PoeteMaudit name参数为序列指定名称,然后重置索引,使非索引列获得该名称。但现在看,你可能更准确了。对不起,不是在我的工作站。