
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements