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

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

## Pandas Time Series: Exercise-12 with Solution

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.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz

﻿

## Python: Tips of the Day

Merging two dicts in Python 3.5+ with a single expression

Example:

```# How to merge two dictionaries
# in Python 3.5+

x = {'p': 1, 'q': 3}
y = {'q': 5, 'r': 8}

z = {**x, **y}

z
{'r': 4, 'p': 1, 'q': 3}

z = dict(x, **y)
print(z)
```

Output:

```{'p': 1, 'q': 5, 'r': 8}
```