w3resource

Pandas: Convert year and day of year into a single datetime column of a dataframe


12. Convert Year and Day of Year to Datetime

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

For more Practice: Solve these Related Problems:

  • Write a Pandas program to merge separate 'year' and 'day-of-year' columns into a single datetime column and handle leap years.
  • Write a Pandas program to convert integer year and day-of-year values into datetime and then sort the DataFrame by the new column.
  • Write a Pandas program to create a DataFrame with year and day-of-year, convert it to datetime, and then filter for a specific month.
  • Write a Pandas program to generate a datetime index from year and day-of-year columns and verify the resulting format.

Go to:


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.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.