w3resource

Pandas: Create a Series of Timestamps from a DataFrame of integer or string columns

Pandas Time Series: Exercise-13 with Solution

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.

Sample Solution:

Python Code :

import pandas as pd
df = pd.DataFrame({'year': [2018, 2019, 2020],
                   'month': [2, 3, 4],
                   'day': [4, 5, 6],
                   'hour': [2, 3, 4]})
print("Original dataframe:")
print(df)
result = pd.to_datetime(df)
print("\nSeries of Timestamps from the said dataframe:")
print(result)
print("\nSeries of Timestamps using specified columns:")
print(pd.to_datetime(df[['year', 'month', 'day']]))

Sample Output:

Original dataframe:
   year  month  day  hour
0  2018      2    4     2
1  2019      3    5     3
2  2020      4    6     4

Series of Timestamps from the said dataframe:
0   2018-02-04 02:00:00
1   2019-03-05 03:00:00
2   2020-04-06 04:00:00
dtype: datetime64[ns]

Series of Timestamps using specified columns:
0   2018-02-04
1   2019-03-05
2   2020-04-06
dtype: datetime64[ns]

Python Code Editor:

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

Previous: Write a Pandas program to convert year and day of year into a single datetime column of a dataframe.
Next: Write a Pandas program to check if a day is a business day (weekday) or not.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/pandas/time-series/pandas-time-series-exercise-13.php