Write a program in Python to split the date column into day, month, year in multiple columns of a given dataframe


Assume, you have a dataframe and the result for a date, month, year column is,

      date  day  month  year
0 17/05/2002 17   05    2002
1 16/02/1990 16   02    1990
2 25/09/1980 25   09    1980
3 11/05/2000 11   05    2000
4 17/09/1986 17   09    1986

To solve this, we will follow the steps given below −

Solution

  • Create a list of dates and assign into dataframe.

  • Apply str.split function inside ‘/’ delimiter to df[‘date’] column. Assign the result to df[[“day”, “month”, “year”]].

Example

Let’s check the following code to get a better understanding −

import pandas as pd
df = pd.DataFrame({
      'date': ['17/05/2002','16/02/1990','25/09/1980','11/05/2000','17/09/1986']
   })
print("Original DataFrame:")
print(df)
df[["day", "month", "year"]] = df["date"].str.split("/", expand = True)
print("\nNew DataFrame:")
print(df)

Output

Original DataFrame:
     date
0 17/05/2002
1 16/02/1990
2 25/09/1980
3 11/05/2000
4 17/09/1986
New DataFrame:
      date  day  month year
0 17/05/2002 17    05 2002
1 16/02/1990 16    02 1990
2 25/09/1980 25    09 1980
3 11/05/2000 11    05 2000
4 17/09/1986 17    09 1986

Updated on: 25-Feb-2021

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements