python中的Split()如果有条件必须跳过某些值,如何使用

2024-09-28 20:54:59 发布

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

我是python新手,我想把数据分成一列,包括电影名称和发行年份,然后分成多列,所以我找到了split函数。你知道吗

数据按标题(年份)组织。你知道吗

我在python中尝试的是:

movies['title'].str.split('(', 1, expand = True)

以下情况例外:

City of Lost Children, The (Cité des enfants perdus, La) (1999)

City of Lost Children, The. Cité des enfants perdus, La) (1999)

我所期待的是1999年)进入第二栏。你知道吗

我需要你的帮助!你知道吗


Tags: ofthe数据city电影lasplit年份
2条回答

我建议pd.Series.str.rsplit

给定一系列s

print(s)
0    City of Lost Children, The (Cité des enfants perdus, La) (1999)
1    'City of Lost Children, The. Cité des enfants perdus, La) (1999)'
dtype: object

使用s.str.rsplit('(', 1, expand=True)

                                                   0      1
0  City of Lost Children, The (Cité des enfants p...  1999)
1  City of Lost Children, The. Cité des enfants p...  1999)

我赞成在这里使用re.findall模式(.*?) \((\d{4})\)

input = """City of Lost Children, The (Cité des enfants perdus, La) (1999)
           City of Lost Children, The. Cité des enfants perdus, La) (1999)"""

matches = re.findall(r'\s*(.*?) \((\d{4})\)', input)
print(matches)

这张照片:

[('City of Lost Children, The (Cité des enfants perdus, La)', '1999'),
 ('City of Lost Children, The. Cité des enfants perdus, La)', '1999')]

相关问题 更多 >