大 pandas 使用正则表达式将列表分为几列 [英] pandas split list into columns with regex
本文介绍了大 pandas 使用正则表达式将列表分为几列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串列表:
content
01/09/15, 10:07 - message1
01/09/15, 10:32 - message2
01/09/15, 10:44 - message3
我想要一个数据框,例如:
I want a data frame, like:
date message
01/09/15, 10:07 message1
01/09/15, 10:32 message2
01/09/15, 10:44 message3
考虑到我列表中所有字符串均以该格式开头的事实,我可以按-
进行拆分,但我希望寻找一种更智能的方法.
Considering the fact that all my strings in the list starts in that format, I can just split by -
, but I rather look for a smarter way to do so.
history = pd.DataFrame([line.split(" - ", 1) for line in content], columns=['date', 'message'])
(之后我将日期转换为日期时间)
(I'll convert the date to date time afterwards)
任何帮助将不胜感激.
Any help would be appreciated.
推荐答案
您可以使用str.extract
-命名组可以成为列名
You can use str.extract
- where named groups can become column names
In [5827]: df['content'].str.extract('(?P<date>[\s\S]+) - (?P<message>[\s\S]+)',
expand=True)
Out[5827]:
date message
0 01/09/15, 10:07 message1
1 01/09/15, 10:32 message2
2 01/09/15, 10:44 message3
详细信息
Details
In [5828]: df
Out[5828]:
content
0 01/09/15, 10:07 - message1
1 01/09/15, 10:32 - message2
2 01/09/15, 10:44 - message3
这篇关于大 pandas 使用正则表达式将列表分为几列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文