【pandas】时间序列_interpolate函数_plot等

本文介绍了Python中时间函数的使用,如to_datetime用于日期解析,to_timedelta用于时间间隔操作。还展示了如何创建日期范围、处理缺失值(interpolate)以及DataFrame操作。涵盖了pd.to_datetime格式化、日期操作、数据填充和数据可视化等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import pandas as pd 
import numpy as np
import matplotlib.pyplot as plt

时间函数相关

to_datetime 
to_datedelta 
date_range 
bdate_range
"""
to_datetime 常用格式 
%d 日期 01, 02, …, 31
%m 月份 01,02,…,12
%Y 年份 2022 
%H 24小时 
%I 12小时 
%M 分钟 
%S 秒钟 
"""
print(pd.to_datetime('20220102 12:21',format='%Y%m%d %H:%M'))
pd.to_datetime('20220102',format='%Y%m%d').strftime('%Y - %d - %m') # strftime 转为字符串
2022-01-02 12:21:00





'2022 - 02 - 01'
"""
to_timedelta 增加时间间隔
周:‘W’
天:‘D’ / ‘days’ / ‘day’
小时:‘hours’ / ‘hour’ / ‘hr’ / ‘h’
分钟:‘m’ / ‘minute’ / ‘min’ / ‘minutes’ / ‘T’
秒:‘S’ / ‘seconds’ / ‘sec’ / ‘second’
"""
pd.to_datetime('20220102',format='%Y%m%d') + pd.to_timedelta('1W'),
(Timestamp('2022-01-09 00:00:00'),)
pd.date_range(start='2022-08-01',end='2022-09-01',freq='D') # fre 同样可以使用W,D,H,S等
DatetimeIndex(['2022-08-01', '2022-08-02', '2022-08-03', '2022-08-04',
               '2022-08-05', '2022-08-06', '2022-08-07', '2022-08-08',
               '2022-08-09', '2022-08-10', '2022-08-11', '2022-08-12',
               '2022-08-13', '2022-08-14', '2022-08-15', '2022-08-16',
               '2022-08-17', '2022-08-18', '2022-08-19', '2022-08-20',
               '2022-08-21', '2022-08-22', '2022-08-23', '2022-08-24',
               '2022-08-25', '2022-08-26', '2022-08-27', '2022-08-28',
               '2022-08-29', '2022-08-30', '2022-08-31', '2022-09-01'],
              dtype='datetime64[ns]', freq='D')
# 使用B时候自动去除周末,等于bdate_range
pd.date_range(start='2022-08-01',end='2022-08-10',freq='B') ==  pd.bdate_range(start='2022-08-01',end='2022-08-10')
array([ True,  True,  True,  True,  True,  True,  True,  True])
# dayofweek  日期为周几
# dayofyear  一年中的第几天 
# weekofyear 一年中第几个周 
# quarter 季度
pd.Series(pd.bdate_range(start='2022-08-01',end='2022-08-10')).dt.quarter
0    3
1    3
2    3
3    3
4    3
5    3
6    3
7    3
dtype: int64

interpolate 缺失值线性填充函数

ts = pd.Series([1,np.nan,7,np.nan,np.nan,np.nan,2,np.nan,11,np.nan,9])
# zero 类似于ffill slinear 线性插样 
plt.figure(figsize=(9,5))
l1 = ts
x = np.arange(len(l1),)
for i in [ 'zero', 'slinear']:
    plt.plot(x,ts.interpolate(method=i,order = 1),label = i,marker = 'o',markersize = 4)
plt.axvline(x=0,ls = '-.',lw = 0.5)
plt.axvline(x=2,ls = '-.',lw = 0.5)
plt.axvline(x=6,ls = '-.',lw = 0.5)
plt.axvline(x=8,ls = '-.',lw = 0.5)
plt.axvline(x=10,ls = '-.',lw = 0.5)
plt.legend(loc = 'upper left')
<matplotlib.legend.Legend at 0x23832342e50>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-l2fTZr7b-1663211083506)(output_10_1.png)]

#  'quadratic' 二阶插样 , 'cubic' 三阶插样 ,'barycentric' 质心插样 
plt.figure(figsize=(9,5))
l1 = ts
x = np.arange(len(l1),)
for i in [ 'quadratic', 'cubic','barycentric']:
    plt.plot(x,ts.interpolate(method=i),label = i,marker = 'o',markersize = 4)
plt.axvline(x=0,ls = '-.',lw = 0.5)
plt.axvline(x=2,ls = '-.',lw = 0.5)
plt.axvline(x=6,ls = '-.',lw = 0.5)
plt.axvline(x=8,ls = '-.',lw = 0.5)
plt.axvline(x=10,ls = '-.',lw = 0.5)
plt.legend()
<matplotlib.legend.Legend at 0x2383bc6ff10>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pyK7CvoG-1663211083518)(output_11_1.png)]

# spline 可以通过指定order 设置多次插样 order 为设置值 
plt.figure(figsize=(9,5))
l1 = ts
x = np.arange(len(l1),)
plt.axvline(x=0,ls = '-.',lw = 0.5)
plt.axvline(x=2,ls = '-.',lw = 0.5)
plt.axvline(x=6,ls = '-.',lw = 0.5)
plt.axvline(x=8,ls = '-.',lw = 0.5)
plt.axvline(x=10,ls = '-.',lw = 0.5)
for i in [1,2,3,4]:
    plt.plot(x,ts.interpolate(method='spline',order = i),label = f'{i} level ',marker = 'o',markersize = 4)
plt.legend(loc = 'upper left')
<matplotlib.legend.Legend at 0x2383dd4a160>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lmxOGV9o-1663211083520)(output_12_1.png)]

plot

ts = pd.Series(np.random.randint(2,10,9),index=[f'col{i}' for i in range(9)])
ts.plot.pie()
<AxesSubplot:ylabel='None'>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tQU26JiN-1663211083522)(output_15_1.png)]

ts.plot.bar()
<AxesSubplot:>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lV2mmY08-1663211083526)(output_16_1.png)]

ts.plot.box()
<AxesSubplot:>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fLrP4k06-1663211083527)(output_17_1.png)]

ts.plot.line()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-oqKNyuKp-1663211083529)(output_18_1.png)]

other

df = pd.DataFrame({'col':np.arange(-10,10,5),'col1':np.random.randint(-10,10,4)}) # set df by ramdom 
df
colcol1
0-10-1
1-56
207
35-9
df.col1.nunique()  # 单一值的个数
4
df.col1.between(2,10)  # 是否在某个区间
0    False
1     True
2     True
3    False
Name: col1, dtype: bool
df.col1.clip(2,10)  # 将不再某一区间的 强制转变为该区间 
0    2
1    6
2    7
3    2
Name: col1, dtype: int32
df.col.is_monotonic  # 判断是否单调 也有单调增加和减少
True
df.col.idxmax(),df.col.argmax() # idxmax 返回索引 argmax 返回整数位置
(3, 3)
df.col.sample(n=2)  # 随机抽样函数 n = 个数 ,frac为比率
2    0
3    5
Name: col, dtype: int32
df.col.duplicated()  # 可选择keep = frist 
0    False
1    False
2    False
3    False
Name: col, dtype: bool

<think>好的,我现在需要帮助用户解决如何用Pandas比较或对齐两个不同的时间序列数据的问题。首先,我得回忆一下Pandas中处理时间序列的相关知识。根据用户提供的引用,特别是引用[2]和[3],用户可能已经知道如何将数据转换为datetime64类型,并且创建时间索引。引用[4]提到的时间相关类,比如Timestamp和DatetimeIndex,应该在这里派上用场。 用户的问题是比较或对齐两个时间序列。常见的场景可能包括数据对齐、计算两个序列之间的差异,或者合并不同频率的数据。首先,我需要确保两个时间序列都已经被正确转换为datetime类型,并且设置为索引。这是处理时间序列数据的基础步骤,如引用[3]所示,使用pd.to_datetime()转换日期列。 接下来,对齐操作可能需要使用reindex方法,或者Pandas的align函数。但需要注意,如果两个时间序列的时间点不完全相同,直接比较会导致缺失值。这时可能需要填充方法,比如前向填充或插值。例如,使用fillna来处理缺失的数据点。 另外,如果两个时间序列的频率不同,比如一个是日数据,另一个是小时数据,可能需要重采样。用户提到的引用[4]中的Period和resample方法可能相关。比如,使用asfreq来调整频率,或者使用resample进行上采样或下采样,然后进行填充。 比较两个序列可能涉及计算差异,比如逐点相减。但必须确保两个序列在相同的时间点上有数据,否则需要先对齐。此外,可视化比较可能也是用户需要的,比如绘制两个序列在同一图表中,观察趋势是否一致。 还需要考虑时区的问题,如果两个时间序列的时区不同,需要用tz_localize和tz_convert进行调整,但用户的问题中没有提到时区,可能暂时不需要处理这部分。 可能的步骤总结: 1. 转换时间为datetime类型并设为索引。 2. 对齐时间索引,处理缺失值。 3. 调整频率(如果需要)。 4. 进行数学比较或合并数据。 5. 可视化比较。 现在要确保这些步骤在Pandas中的具体实现方法正确。例如,使用df1.reindex(df2.index)来对齐索引,或者使用df1.align(df2, join='outer')来获取对齐后的数据。对于填充,fillna的参数如method='ffill'或指定固定值。 还要考虑用户可能遇到的常见问题,例如数据重叠部分如何处理,或者如何计算统计指标(如相关系数)来比较两个序列的相关性。此外,合并数据时可能需要使用merge或concat,但时间序列通常用join,特别是按索引连接。 生成相关问题的时候,需要围绕用户的问题扩展,比如如何合并不同频率的数据,如何处理缺失值,或者如何计算两个序列的相关性等。</think>要比较或对齐两个不同的时间序列数据,可以通过以下步骤实现: --- ### 1. **时间索引标准化** 将两个时间序列的时间列转换为 `datetime64[ns]` 类型,并设为索引: ```python import pandas as pd # 假设 df1 和 df2 是两个时间序列数据 df1['time'] = pd.to_datetime(df1['time']) # 转换时间列[^3] df2['time'] = pd.to_datetime(df2['time']) df1.set_index('time', inplace=True) # 设为索引 df2.set_index('time', inplace=True) ``` --- ### 2. **对齐时间索引** 使用 `reindex` 或 `align` 对齐两个序列的时间点: ```python # 方法1:对齐到两个序列的并集时间点 df1_aligned, df2_aligned = df1.align(df2, join='outer') # 方法2:对齐到其中一个序列的时间点(如df1) df2_reindexed = df2.reindex(df1.index) ``` --- ### 3. **处理缺失值** 对齐后可能出现缺失值(NaN),需填充或插值: ```python # 前向填充 df2_filled = df2_reindexed.ffill() # 线性插值 df2_interpolated = df2_reindexed.interpolate() ``` --- ### 4. **频率调整(如不同采样率)** 若序列频率不同(如日数据 vs 小时数据),使用 `asfreq` 或 `resample`: ```python # 将df1从日数据降采样到周数据 df1_weekly = df1.resample('W').mean() # 将df2从小时数据升采样到分钟数据(填充缺失值) df2_minute = df2.resample('T').ffill() ``` --- ### 5. **数学比较或合并** 直接进行数学运算或合并数据: ```python # 计算差异(需时间点对齐) difference = df1_aligned['value'] - df2_aligned['value'] # 合并两个序列(横向合并) combined = pd.concat([df1, df2], axis=1, keys=['series1', 'series2']) ``` --- ### 6. **可视化对比** 用 Matplotlib 或 Pandas 内置绘图功能观察趋势: ```python import matplotlib.pyplot as plt df1['value'].plot(label='Series1') df2['value'].plot(label='Series2') plt.legend() plt.show() ``` --- ### 关键函数说明 | 方法 | 作用 | |--------------------|----------------------------------------| | `pd.to_datetime()` | 将字符串/列转换为时间类型[^2][^3] | | `df.align()` | 对齐两个数据集的时间索引 | | `df.reindex()` | 按指定索引重新排列数据 | | `df.resample()` | 调整时间序列频率(上采样/下采样)[^4] |
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值