Spencer Timothy
Spencer Timothy

Reputation: 37

Splitting a Pandas DataFrame column into two columns

I'm working on a simple web scrape, DataFrame project. I have a simple 8x1 DataFrame, and I'm trying to split it into an 8x2 DataFrame. So far this is what my DataFrame looks like:

dframe = DataFrame(data, columns=['Active NPGL Teams'], index=[1, 2, 3, 4, 5, 6, 7, 8])
    Active NPGL Teams
1   Baltimore Anthem (2015–present)
2   Boston Iron (2014–present)
3   DC Brawlers (2014–present)
4   Los Angeles Reign (2014–present)
5   Miami Surge (2014–present)
6   New York Rhinos (2014–present)
7   Phoenix Rise (2014–present)
8   San Francisco Fire (2014–present)

I would like to add a column, "Years Active" and split the "(2014-present)", "(2015-present)" into the "Years Active" column. How do I split my data?

Upvotes: 0

Views: 514

Answers (1)

Igor Raush
Igor Raush

Reputation: 15240

You can use

dframe['Active NPGL Teams'].str.split(r' (?=\()', expand=True)
                    0               1
1    Baltimore Anthem  (2015–present)
2         Boston Iron  (2014–present)
3         DC Brawlers  (2014–present)
4   Los Angeles Reign  (2014–present)
5         Miami Surge  (2014–present)
6     New York Rhinos  (2014–present)
7        Phoenix Rise  (2014–present)
8  San Francisco Fire  (2014–present)

The key is the regex r' (?=\()' which matches a space only if it is followed by an open parenthesis (lookahead assertion).


Another approach (which is about 5% slower but more flexible) is to user Series.str.extract.

dframe['Active NPGL Teams'].str.extract(r'^(?P<Team>.+) (?P<YearsActive>\(.+\))$',
                                        expand=True)
                 Team     YearsActive
1    Baltimore Anthem  (2015–present)
2         Boston Iron  (2014–present)
3         DC Brawlers  (2014–present)
4   Los Angeles Reign  (2014–present)
5         Miami Surge  (2014–present)
6     New York Rhinos  (2014–present)
7        Phoenix Rise  (2014–present)
8  San Francisco Fire  (2014–present)

Upvotes: 2

Related Questions