您没有确切地说明数据是如何存储的,所以我假设您有一堆与上面的类似的项,这些项是通过在文件中读取并在新行上拆分得到的。这将提供一个类似示例数据的字符串。在
将该字符串传递给函数: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与{}一起使用。在