Time series data is one of the most common forms of data encountered in data science, finance, and business analytics. A time series is a series of data points indexed in time order, typically equally spaced in intervals like days, months, or years. Python, through the Pandas library, provides robust support for working with time series and date/time functionality.
In this document, we explore time series analysis capabilities in Python, focusing on:
from datetime import datetime, date, time
dt = datetime(2023, 5, 15, 12, 30)
d = date(2023, 5, 15)
t = time(12, 30)
print(dt)
print(d)
print(t)
now = datetime.now()
today = date.today()
print(now)
print(today)
from datetime import timedelta
dt1 = datetime(2023, 5, 15)
dt2 = dt1 + timedelta(days=10)
print(dt2)
import pandas as pd
dates = pd.date_range(start='2023-01-01', periods=5, freq='D')
values = [100, 102, 98, 105, 110]
ts = pd.Series(values, index=dates)
print(ts)
Pandas automatically creates a DatetimeIndex if the index is a date range.
print(ts.index)
print(ts['2023-01-03'])
print(ts['2023-01'])
df = pd.DataFrame({
'date': ['2023-01-01', '2023-01-02', '2023-01-03'],
'value': [10, 20, 30]
})
df['date'] = pd.to_datetime(df['date'])
print(df.dtypes)
df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d')
date_range = pd.date_range(start='2023-01-01', end='2023-01-10', freq='D')
print(date_range)
print(ts['2023-01-01'])
print(ts['2023-01-01':'2023-01-03'])
print(ts[ts > 100])
print(ts.loc['2023-01-04'])
monthly = ts.resample('M').mean()
print(monthly)
Converting from high to low frequency (e.g., daily to monthly).
downsampled = ts.resample('2D').sum()
print(downsampled)
Converting from low to high frequency.
upsampled = ts.resample('H').ffill()
print(upsampled.head(10))
rolling = ts.rolling(window=2).mean()
print(rolling)
expanding = ts.expanding().mean()
print(expanding)
custom = ts.rolling(window=3).apply(lambda x: max(x) - min(x))
print(custom)
shifted = ts.shift(1)
print(shifted)
diff = ts - ts.shift(1)
print(diff)
lead = ts.shift(-1)
print(lead)
localized = ts.tz_localize('UTC')
print(localized)
converted = localized.tz_convert('Asia/Kolkata')
print(converted)
dt_with_tz = pd.to_datetime('2023-01-01 10:00').tz_localize('US/Eastern')
print(dt_with_tz)
period = pd.Period('2023-01', freq='M')
print(period)
pindex = pd.period_range(start='2023-01', periods=4, freq='Q')
print(pindex)
values = [100, 120, 130, 140]
ts_period = pd.Series(values, index=pindex)
print(ts_period)
ts_from_period = ts_period.to_timestamp()
print(ts_from_period)
ts_to_period = ts.to_period('M')
print(ts_to_period)
ts_missing = ts.reindex(pd.date_range('2023-01-01', '2023-01-10'))
print(ts_missing)
filled = ts_missing.ffill()
print(filled)
interpolated = ts_missing.interpolate()
print(interpolated)
import matplotlib.pyplot as plt
ts.plot(title='Sample Time Series')
plt.xlabel('Date')
plt.ylabel('Value')
plt.show()
stock_data = pd.DataFrame({
'date': pd.date_range(start='2023-01-01', periods=5, freq='B'),
'price': [100, 102, 105, 107, 110]
})
stock_data.set_index('date', inplace=True)
returns = stock_data['price'].pct_change()
print(returns)
traffic = pd.Series([200, 240, 250, 300, 280],
index=pd.date_range('2023-03-01', periods=5, freq='D'))
print(traffic.rolling(window=3).mean())
iot_data = pd.Series([25.0, 25.5, 26.1, 26.4, 26.9],
index=pd.date_range('2023-06-01 00:00', periods=5, freq='H'))
print(iot_data.resample('2H').mean())
Time series analysis is fundamental in data science. Whether you are forecasting sales, tracking web traffic, or analyzing stock prices, mastering Pythonβs time and date functionalities is essential. With Pandas, Python provides a full set of tools to handle timestamps, periods, resampling, and time zone-aware data. By understanding time series indexing, resampling, rolling statistics, and missing data handling, you will be well-equipped to manage and analyze temporal data with confidence.
Python is commonly used for developing websites and software, task automation, data analysis, and data visualisation. Since it's relatively easy to learn, Python has been adopted by many non-programmers, such as accountants and scientists, for a variety of everyday tasks, like organising finances.
Learning Curve: Python is generally considered easier to learn for beginners due to its simplicity, while Java is more complex but provides a deeper understanding of how programming works.
The point is that Java is more complicated to learn than Python. It doesn't matter the order. You will have to do some things in Java that you don't in Python. The general programming skills you learn from using either language will transfer to another.
Read on for tips on how to maximize your learning. In general, it takes around two to six months to learn the fundamentals of Python. But you can learn enough to write your first short program in a matter of minutes. Developing mastery of Python's vast array of libraries can take months or years.
6 Top Tips for Learning Python
The following is a step-by-step guide for beginners interested in learning Python using Windows.
Best YouTube Channels to Learn Python
Write your first Python programStart by writing a simple Python program, such as a classic "Hello, World!" script. This process will help you understand the syntax and structure of Python code.
The average salary for Python Developer is βΉ5,55,000 per year in the India. The average additional cash compensation for a Python Developer is within a range from βΉ3,000 - βΉ1,20,000.
Copyrights © 2024 letsupdateskills All rights reserved