Skip to main content
 首页 » 编程设计

python之如何让 Pandas 系列只绘制索引中的数据

2025年05月04日14lidabo

编辑 预计会错过日期 20140103 和 20140104,我不希望它们自动修补。 而且我不想使用 xs = pd.Series(data=range(len(ts)), index=pd.to_datetime(ts)) 而不是 xs = pd.Series (data=range(len(ts)), index=pd.to_datetime(ts)) 因为我想使用一些操作作为

xs = pd.Series(data=range(len(ts)), index=pd.to_datetime(ts)) 
 
xs['2014'] 
Out[24]:  
2014-01-01    0 
2014-01-02    1 
2014-01-05    2 
2014-01-06    3 
2014-01-07    4 
dtype: int64 

不适用于:

In [26]: xs = pd.Series(data=range(len(ts)), index=ts) 
 
In [27]: xs['2014'] 
--------------------------------------------------------------------------- 
KeyError: '2014' 

例如:

In [1]: import pandas as pd 
 
In [2]: ts = ['20140101', '20140102', '20140105', '20140106', '20140107'] 
 
In [3]: xs = pd.Series(data=range(len(ts)), index=pd.to_datetime(ts)) 
 
In [4]: xs.plot() 

将绘制此图像,其中添加了关于 20140103、20140104 的额外数据。

虽然我想要这样的图像:

import matplotlib.pyplot as plt 
 
plt.plot(xs.values) 

请您参考如下方法:

感谢 euri10 use_index = False

ts = ['20140101', '20140102', '20140105', '20140106', '20140107'] 
xs = pd.Series(data=range(len(ts)), index=pd.to_datetime(ts)) 
fig, ax = plt.subplots() 
xs.plot(use_index=False) 
ax.set_xticklabels(pd.to_datetime(ts)) 
ax.set_xticks(range(len(ts))) 
fig.autofmt_xdate() 
plt.show()