How to create a series with DateTime?

PandasServer Side ProgrammingProgramming

One of the common data for pandas is date-time, pandas have a different set of functionalities to perform any task related to work on date-time data.

Pandas have date_range functions for generating a sequence of dates in a particular order, at the same time it has many other functions to work with these date-time data.

We can create a pandas series object by using date-time data, let’s see an example for creating a pandas Series using date-time values.

Example

import pandas as pd

# creating range sequence of dates
dates = pd.date_range('2021-06-14', periods=5, freq='D')

#creating pandas Series with date index
s = pd.Series(dates)
print (s)

Explanation

Initially, we imported the pandas module into our workspace by using the python import keyword, then we created a sequence of dates by using the date range function, and those dates are stored in a variable called dates.

We have sent this dates variable to the pandas series constructor, which will create a pandas series object like the output below.

Output

0   2021-06-14
1   2021-06-15
2   2021-06-16
3   2021-06-17
4   2021-06-18
dtype: datetime64[ns]

The resultant pandas series object can be seen in the above block, which has a sequence of dates from 2021-06-14 to 2021-06-18. In the code block, we have defined starting dates and periods equal to 5 based on the inputs these 5 sets of dates are generated. And the index values are auto-created values from 0 to 4.

Example

import pandas as pd
import numpy as np

# creating range sequence of dates
date = pd.date_range('2021-06-14', periods=5, freq='D')

#creating pandas Series with date index
s = pd.Series(np.random.randn(len(date)), index=date)
print (s)

Explanation

In this above example, we have created a pandas Series with DateTime as an index value and Series data is some random numbers generated by using the NumPy random function.

To achieve this initially, we imported the required packages which are pandas and NumPy. After that, we have generated dates by using the pandas data_range function. Using these dates, we created a pandas series and the index values are our dates, and data are random values.

Output

2021-06-14   0.701791
2021-06-15  -1.731610
2021-06-16  -3.377266
2021-06-17  -0.138523
2021-06-18  -0.160986
Freq: D, dtype: float64

The dates are index labels and values are random numbers, here we can see that the dtype of series data (values) is float64, and Freq: D is representing the frequency of our index labels.

raja
Updated on 17-Nov-2021 07:25:08

Advertisements