Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas split list into columns with regex

I have a string list:

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.

like image 697
sheldonzy Avatar asked Oct 25 '17 09:10

sheldonzy


1 Answers

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
like image 199
Zero Avatar answered Oct 19 '22 08:10

Zero