Python 如何在熊猫数据帧中堆叠wthin以执行其引用?

Python 如何在熊猫数据帧中堆叠wthin以执行其引用?,python,string,python-3.x,pandas,Python,String,Python 3.x,Pandas,我有一个包含大量文档的大熊猫数据框架: id text 1 doc2 Google i... 2 doc3 Amazon... 3 doc4 This was... ... n docN nice camara... 如何将所有文档堆叠成句子,执行各自的id?: id text 1 doc1 Google is a great company. 2 doc1 It is in silicon valley. 3 d

我有一个包含大量文档的大熊猫数据框架:

    id  text
1   doc2    Google i...
2   doc3    Amazon...
3   doc4    This was...
...
n   docN    nice camara...
如何将所有文档堆叠成句子,执行各自的id?:

    id  text
1   doc1   Google is a great company.
2   doc1   It is in silicon valley.
3   doc1   Their search engine is the best
4   doc2   Amazon is a great store.
5   doc2   it is located in Seattle.
6   doc2   its new product is alexa. 
5   doc2   its expensive.
5   doc3   This was a great product.
...
n   docN   nice camara I really liked it.
我试图:

import nltk
def sentence(document):
    sentences = nltk.sent_tokenize(document.strip(' '))
    return sentences


df['sentece'] = df['text'].apply(sentence)
df.stack(level=0)

然而,它没有起作用。有没有关于如何堆叠执行其出处id的句子的想法?

这将使用
apply
对每个句子进行迭代,以便它可以使用
nltk.sent\u tokenize
。然后,它使用序列构造函数将所有句子转换为它们自己的列

df1 = df['text'].apply(lambda x: pd.Series(nltk.sent_tokenize(x)))
df1.set_index(df['id']).stack()
假数据示例
这里有一个类似于您的问题的解决方案:。以下是我对您的特定任务的解释:

df['sents'] = df['text'].apply(lambda x: nltk.sent_tokenize(x))
s = df.apply(lambda x: pd.Series(x['sents']), axis=1).stack().\
                                 reset_index(level=1, drop=True)
s.name = 'sents'
df = df.drop(['sents','text'], axis=1).join(s)

我想你会发现如果你把你的团队不在熊猫里,这会容易得多。这是我的解决办法。最后,我将其重新装配到熊猫数据框中。我认为这可能是最具可扩展性的解决方案

def stack(one, two):
    sp = two.split(".")
    return [(one, a.strip()) for a in sp if len(a.strip()) > 0]

st = sum(map(stack, df['id'].tolist(),df['text'].tolist()),[])

df2 = pd.DataFrame(st)

df2.columns = ['id','text']
如果你想添加一个句子Id列,你可以做一些小的调整

def stack(one, two):
    sp = two.split(".")
    return [(one, b, a.strip()) for a,b in zip(sp,xrange(1,len(sp)+1)) if len(a.strip()) > 0]

st = sum(map(stack, df['id'].tolist(),df['text'].tolist()),[])

df2 = pd.DataFrame(gen)

df2.columns = ['id','sentence_id','text']

第一帧和第二帧之间的区别是什么?接下来,如果您提供一个小的、可复制的示例来说明您的问题,这将非常有用。请看一下提示。第二个是一个数据框架,包含文档中的所有句子,执行它们各自的id。@DYZAlso,我想用nltk将文本逐句拆分,按句点拆分就可以了。尽管如此,它不会产生与nltk函数相同的结果。请检查我使用nltk.sent_tokeniz的更新答案这实际上是有效的。非常感谢你!,您能解释一下stack()的用法和reset_index吗?
。stack()用数据帧行索引替换系列列索引,本质上是“转置”系列
.reset_index()
将第二级索引转换为列,然后将其删除。
def stack(one, two):
    sp = two.split(".")
    return [(one, b, a.strip()) for a,b in zip(sp,xrange(1,len(sp)+1)) if len(a.strip()) > 0]

st = sum(map(stack, df['id'].tolist(),df['text'].tolist()),[])

df2 = pd.DataFrame(gen)

df2.columns = ['id','sentence_id','text']