2025年07月16日/ 浏览 6
记得刚入行数据分析时,我接到的第一个任务就是分析某电商平台的销售波动。当看到数据中那个”2023-01-01″的日期字段时,才意识到时间序列分析远不只是简单的折线图。时间戳里藏着用户行为模式、系统负载规律甚至金融市场脉搏,而Pandas正是解开这些秘密的钥匙。
python
import pandas as pd
datestr = “2023-07-15 14:30:00”
timestamp = pd.todatetime(date_str)
print(f”时区感知:{timestamp.tz is None}”) # 输出False表示无时区
daterng = pd.daterange(start=’1/1/2023′, end=’1/08/2023′, freq=’D’)
踩坑提醒:处理国际数据时务必注意时区问题,建议先用tz_localize
设置时区,再用tz_convert
转换。
某气象站每小时采集的温度数据:
python
tempdata = [20 + np.random.randn() for _ in range(168)]
timeindex = pd.daterange(‘2023-01-01′, periods=168, freq=’H’)
tempseries = pd.Series(tempdata, index=timeindex)
dailymean = tempseries.resample(‘D’).mean()
分析股票7日移动平均线:
python
import yfinance as yf
aapl = yf.download(‘AAPL’, start=’2022-01-01′)[‘Close’]
ma7 = aapl.rolling(window=7).mean()
ma30 = aapl.rolling(window=30).mean()
plt.plot(aapl, label=’Actual Price’)
plt.plot(ma7, label=’7-day MA’)
plt.plot(ma30, label=’30-day MA’)
处理节假日效应的小技巧:
python
from pandas.tseries.offsets import BDay
currentdate = pd.todatetime(‘2023-05-01’) # 劳动节假期
nextbusinessday = current_date + BDay(1)
python
salesdata = pd.readcsv(‘sales.csv’,
parsedates=[‘timestamp’],
indexcol=’timestamp’)
salesdata = salesdata.asfreq(‘D’, method=’pad’)
python
from statsmodels.tsa.seasonal import seasonal_decompose
result = seasonaldecompose(salesdata[‘sales’], model=’additive’, period=7)
result.plot()
当处理千万级时间序列数据时:
period
替代datetime
节省内存pd.SparseArray
resample(...).parallel_apply()
总结:时间序列就像一本用时间编码的密码本,Pandas提供了完整的解码工具链。记得第一次成功预测出销售额走势时的兴奋感——这或许就是数据科学最迷人的地方。现在,轮到您打开Jupyter Notebook开始探索了!