Minh-Long Luu
Minh-Long Luu

Reputation: 2751

Pandas: split string in a pythonic way

I have a pandas Series date that looks like this:

date       | ...
09.01.2000 |
02.02.2000 |
...

The format is DD-MM-YYYY. I want to split them into three columns Day, Month and Year. I tried:

col = date["date"].str.split(".", expand = True)
date["day"] = col[0]
date["month"] = col[1]
...

It is quite inconvenient so is there a more pythonic way? I also tried pd.to_datetime but that is not the short way.

Upvotes: 2

Views: 795

Answers (3)

Joe Ferndz
Joe Ferndz

Reputation: 8508

You can do something like this.

import pandas as pd
df = pd.DataFrame({'date':['09.01.2000', '02.02.2000']})

df['mon'],df['day'],df['year'] = zip(*df['date'].str.split('.'))
print (df)

It will give you the below dataframe. If you don't want df['date'], then you can use drop() function to drop the column.

         date mon day  year
0  09.01.2000  09  01  2000
1  02.02.2000  02  02  2000

Upvotes: 1

Shubham Sharma
Shubham Sharma

Reputation: 71707

You can do multiple column assignments in a single line:

df[['day', 'month', 'year']] = df['date'].str.split('.', expand=True)

         date day month  year
0  09.01.2000  09    01  2000
1  02.02.2000  02    02  2000

Upvotes: 4

Code-Apprentice
Code-Apprentice

Reputation: 83577

One option is to use a single assignment:

date['date'], date['month'] = col

This assumes that split() returns a list with exactly two elements.

Upvotes: 2

Related Questions