为dataframe中与其他列相关的列编制索引,并

2024-06-16 13:44:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我提供了这个数据框, enter image description here

enter image description here

正如你们看到的,我有3个索引章节,ParaIndex,(段落索引)和Sentindex(sententcesindex),我有70个章节,1699个段落和6999个句子

所以它们都从一开始(0或1)开始,问题是我想制作一个小部件来调用一个“特定句子”,它放在一章的特定段落中。像这样的

https://towardsdatascience.com/interactive-controls-for-jupyter-notebooks-f5c94829aee6 而是在特定章节的特定段落中提取特定的句子

我想我应该有另一个索引(比如chapparsant的缩写)或者甚至是多维索引来显示这个句子的确切位置

你知道我如何使用ipywidget提供吗 https://ipywidgets.readthedocs.io/en/latest/examples/Using%20Interact.html

@interact
def showDetail( Chapter=(1,70),ParaIndex=(0,1699),SentIndex=(0,6999)):
    return df.loc[(df.Chapter == Chapter) & (df.ParaIndex==ParaIndex)&(df.SentIndex==SentIndex)]

这个问题是因为我们不知道每一章有多少段落,也不知道每一段落有多少段落,我们也不知道索引从哪个数字开始,大多数时候我们没有结果

其目的是采用这种方式(或定义一个新的索引),通过改变工具栏按钮,我们总是有一个独特的句子

例如,这里我有一个结果:

enter image description here

但当我换成这个的时候:

[3]: https://i.stack.imgur.com/CdKX0.jpg 我没有任何结果,原因很明显,因为我们没有任何索引1-2-1,因为在第1章第2段中,索引2:Sentindex从2开始

我看到的一个解决方案是一个多维数据帧的完整定义,但我需要一些更简单的东西,我可以使用ipywidget

非常感谢


Tags: 数据httpsdf定义部件句子chapter段落
1条回答
网友
1楼 · 发布于 2024-06-16 13:44:30

我相信有一个更简单的解决办法,但我想这是可行的

import pandas as pd

data = [
dict(Chapter=0, ParaIndex=0, SentIndex=0, content="0"),
dict(Chapter=1, ParaIndex=1, SentIndex=1, content="a"),
dict(Chapter=1, ParaIndex=1, SentIndex=2, content="b"),
dict(Chapter=2, ParaIndex=2, SentIndex=3, content="c"),
dict(Chapter=2, ParaIndex=2, SentIndex=4, content="d"),
dict(Chapter=2, ParaIndex=3, SentIndex=5, content="e"),
dict(Chapter=3, ParaIndex=4, SentIndex=6, content="f"),
    ]


df = pd.DataFrame(data)

enter image description here

def showbyindex(target_chapter, target_paragraph, target_sentence):

    df_chapter = df.loc[df.Chapter==target_chapter]
    unique_paragraphs = df_chapter.ParaIndex.unique()
    paragraph_idx = unique_paragraphs[target_paragraph]

    df_paragraph = df_chapter.loc[df.ParaIndex==paragraph_idx]

    return df_paragraph.iloc[target_sentence]



showbyindex(target_chapter=2, target_paragraph=0, target_sentence=1)

enter image description here

编辑: 如果希望滑块仅在有效范围内,可以为interact decorator定义IntSliders:

chapter_slider = widgets.IntSlider(min=0, max=max(df.Chapter.unique()), step=1, value=0)
paragraph_slider = widgets.IntSlider(min=0, max=1, step=1, value=0)
sentence_slider = widgets.IntSlider(min=0, max=1, step=1, value=0)


@interact(target_chapter=chapter_slider, target_paragraph=paragraph_slider, target_sentence=sentence_slider)

现在,您必须检查showbyindex函数中段落/句子的有效数量,并相应地设置滑块值/max

if(...):
    paragraph_slider.max = ...
...

相关问题 更多 >