pandas 将列表拆分为带有正则表达式的列 [英] pandas split list into columns with regex

查看:25
本文介绍了 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)

任何帮助将不胜感激.

推荐答案

您可以使用 str.extract - 其中命名组可以成为列名

You can use str.extract - where named groups can become column names

In [5827]: df['content'].str.extract('(?P<date>[sS]+) - (?P<message>[sS]+)', 
                                     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

<小时>

详情

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆