如何在python/pandas中以段落形式读取数据?

2024-09-30 01:34:03 发布

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

我用这种格式保存了几年的数据,每个新年用一个空行隔开:

    2014
    #34 - Show Title
    Ensemble: ActorFirst1 ActorLast1, ActorFirst2 ActorLast2, ActorFirst3 ActorLast3, ActorFirst4 ActorLast4, ActorFirst5 ActorLast5, ActorFirst6 ActorLast6, and ActorFirst7 ActorLast7
    Director: DirectorFirst1 DirectorLast1
    Music Director: MDFirst1 MDFirst1
    Stage Manager: SMFirst1 SMFirst1
    Producer: ProducerFirst1 ProducerFirst1
    Opening Night: December 16, 2014

我试图把它变成数据帧中的行的形式

年度,个人1个人,职位,显示职位

我不知道怎么做,一直走到死胡同。在


Tags: 数据title格式show职位directorensemble空行
1条回答
网友
1楼 · 发布于 2024-09-30 01:34:03

您没有确切地说明数据是如何存储的,所以我假设您有一堆与上面的类似的项,这些项是通过在文件中读取并在新行上拆分得到的。这将提供一个类似示例数据的字符串。在

将该字符串传递给函数:

def read_year(f):
    f = iter(f.split('\n'))  # split the string, going to iterate over it

    year = next(f).strip()
    title = next(f).strip()  # maybe split at the '-', dunno if that's part of the title

    # don't need opening date, so iterate till we get there.
    people = takewhile(lambda x: not x.strip().startswith('Opening'), f)
    # setting up for getting (kind, individual)
    people = (tuple(x.split(':')) for x in people) 

    both = []
    for kind, persons in people:
        kind_ = kind.strip()
        for person in persons.strip().split(' '):
            if person != 'and':
                both.append((kind_, person.strip().strip(',')))

    df = pd.DataFrame(both, columns=['person_title', 'person'])
    df['year'] = int(year)
    df['movie_title'] = title
    return df

基本上,在每个字符串上调用该函数

^{pr2}$

然后pd.concat与{}一起使用。在

相关问题 更多 >

    热门问题