Preparation
Before any data manipulation can occur, one (1) new library will require installation.
- The Pandas library enables access to/from a DataFrame.
To install this library, navigate to an IDE terminal. At the command prompt ($
), execute the code below. For the terminal used in this example, the command prompt is a dollar sign ($
). Your terminal prompt may be different.
π‘ Note: The pytz
comes packaged with pandas and does not require installation. However, this library is needed for the tz_ localize()
and tz_convert()
methods to work.
$ pip install pandas
Hit the <Enter>
key on the keyboard to start the installation process.
If the installation was successful, a message displays in the terminal indicating the same.
Feel free to view the PyCharm installation guide for the required library.
Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.
import pandas as pd import pytz
DataFrame to_timestamp()
The to_timestamp()
method casts (converts) data to a Datetimeindex
of timestamps at the start of a selected period.
The syntax for this method is as follows:
DataFrame.to_timestamp(freq=None, how='start', axis=0, copy=True)
Parameter | Description |
---|---|
freq | This parameter is an available frequency of the PeriodIndex method. |
how | This parameter is the period conversion to timestamp. The available options are: 'start' , 'end' , 's' , or 'e' . |
axis | If zero (0) or index is selected, apply to each column. Default 0. If one (1) apply to each row. |
copy | If True , this parameter makes a copy. |
For this example, we have four quarter earnings for Rivers Clothing for 2021. Each row displays a quarter-end date and total earning amount for that time.
earnings = [120545, 230574, 101155, 17598] the_range = pd.period_range('2021Q1', '2021Q4', freq='Q-DEC') times = pd.Series(earnings, the_range) times.index = (the_range.asfreq('M', 'e')).asfreq('H', 's')+8 print(times)
- Line [1] saves the quarterly earnings for Rivers Clothing in 2021 to a list.
- Line [2] sets the date range (quarterly) and frequency. This output saves to the_range.
- Line [3] sets the index and asfreq() month and hour. The start hour for each quarter is 8:00 am.
- Line [4] outputs the times variable to the terminal.
Output
times
2021-03-01 08:00 | 120545 |
2021-06-01 08:00 | 230574 |
2021-09-01 08:00 | 101155 |
2021-12-01 08:00 | 17598 |
Freq: H, dtype: int64 |
More Pandas DataFrame Methods
Feel free to learn more about the previous and next pandas DataFrame methods (alphabetically) here:
Also, check out the full cheat sheet overview of all Pandas DataFrame methods.