Pandas: Convert year and day of year into a single datetime column of a dataframe
Write a Pandas program to convert year and day of year into a single datetime column of a dataframe.
Sample Solution:
Python Code :
import pandas as pd
data = {\
"year": [2002, 2003, 2015, 2018],
"day_of_the_year": [250, 365, 1, 140]
}
df = pd.DataFrame(data)
print("Original DataFrame:")
print(df)
df["combined"] = df["year"]*1000 + df["day_of_the_year"]
df["date"] = pd.to_datetime(df["combined"], format = "%Y%j")
print("\nNew DataFrame:")
print(df)
Sample Output:
Original DataFrame: year day_of_the_year 0 2002 250 1 2003 365 2 2015 1 3 2018 140 New DataFrame: year day_of_the_year combined date 0 2002 250 2002250 2002-09-07 1 2003 365 2003365 2003-12-31 2 2015 1 2015001 2015-01-01 3 2018 140 2018140 2018-05-20
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Pandas program to create a sequence of durations increasing by an hour.
Next: Write a Pandas program to create a series of Timestamps from a DataFrame of integer or string columns. Also create a series of Timestamps using specified columns.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics