【问题标题】:Date is not displayed correctly when plot pandas dataframe绘制熊猫数据框时日期显示不正确
【发布时间】:2013-01-08 22:00:37
【问题描述】:

首先,如果我使用 DataReader 读取数据,然后进行绘图,一切都很好

In [55]: t = DataReader('SPY','yahoo', start=datetime.datetime(1990,1,1))

In [56]: t
Out[56]: 
<class 'pandas.core.frame.DataFrame'>
Index: 5033 entries, 1993-01-29 00:00:00 to 2013-01-23 00:00:00
Data columns:
Open         5033  non-null values
High         5033  non-null values
Low          5033  non-null values
Close        5033  non-null values
Volume       5033  non-null values
Adj Close    5033  non-null values
dtypes: float64(5), int64(1)

In [58]: t.plot()
Out[58]: <matplotlib.axes.AxesSubplot at 0x8cca790>

但是,如果我将它保存为 csv 文件并重新加载它,我会收到错误消息,并且情节也不完全正确,

In [62]: t.to_csv('spy.csv')

In [63]: s = pd.read_csv('spy.csv', na_values=[" "])

In [64]: s.set_index('Date')
Out[64]: 
<class 'pandas.core.frame.DataFrame'>
Index: 5033 entries, 1993-01-29 00:00:00 to 2013-01-23 00:00:00
Data columns:
Open         5033  non-null values
High         5033  non-null values
Low          5033  non-null values
Close        5033  non-null values
Volume       5033  non-null values
Adj Close    5033  non-null values
dtypes: float64(5), int64(1)

In [66]: s.plot()                                                            
--------------------------------------------------------------------------- 
AttributeError                            Traceback (most recent call last) 
/home/dli/pythonTest/pandas/<ipython-input-66-d3eb09d34df4> in <module>()   
----> 1 s.plot()                                                            

/usr/lib/pymodules/python2.7/pandas/core/frame.pyc in plot(self, subplots, sharex, sharey, use_index, figsize, grid, legend, rot, ax, kind, **kwds)
3748                     ax.legend(loc='best')                              
3749                 else:                                                  
-> 3750                     ax.plot(x, y, label=str(col), **kwds)           
3751                                                                        
3752                 ax.grid(grid)                                          

/usr/lib/pymodules/python2.7/matplotlib/axes.pyc in plot(self, *args, **kwargs)
3891         lines = []                                                     
3892                                                                        
-> 3893         for line in self._get_lines(*args, **kwargs):               
3894             self.add_line(line)                                        
3895             lines.append(line)                                         

/usr/lib/pymodules/python2.7/matplotlib/axes.pyc in _grab_next_args(self, *args, **kwargs)
    320                 return                                              
    321             if len(remaining) <= 3:                                 
--> 322                 for seg in self._plot_args(remaining, kwargs):      
    323                     yield seg                                       
    324                 return                                              

/usr/lib/pymodules/python2.7/matplotlib/axes.pyc in _plot_args(self, tup, kwargs)
    279         ret = []                                                    
    280         if len(tup) > 1 and is_string_like(tup[-1]):                
--> 281             linestyle, marker, color = _process_plot_format(tup[-1])
    282             tup = tup[:-1]                                          
    283         elif len(tup) == 3:                                         

/usr/lib/pymodules/python2.7/matplotlib/axes.pyc in _process_plot_format(fmt)
    93     # handle the multi char special cases and strip them from the    

    94     # string                                                         

---> 95     if fmt.find('--')>=0:                                           
    96         linestyle = '--'                                             
    97         fmt = fmt.replace('--', '')                                  

AttributeError: 'numpy.ndarray' object has no attribute 'find'            

知道怎么解决吗?

谢谢。 丹

【问题讨论】:

    标签: matplotlib dataframe pandas


    【解决方案1】:

    set_index 方法返回默认情况下是一个新的 DataFrame,而不是就地应用这个(事实上,大多数 pandas 函数都是类似的)。它有一个inplace 参数:

    s.set_index('Date', inplace=True)
    s.plot()
    

    效果如你所愿!

    注意:要将索引转换为 DatetimeIndex,您可以使用to_datetime

    s.index = s.index.to_datetime()
    

    .

    也就是说,s被你保持不变.set_index('Date')

    In [63]: s = pd.read_csv('spy.csv', na_values=[" "])
    
    In [64]: s.set_index('Date')
    Out[64]: 
    <class 'pandas.core.frame.DataFrame'>
    Index: 5033 entries, 1993-01-29 00:00:00 to 2013-01-23 00:00:00
    Data columns:
    Open         5033  non-null values
    High         5033  non-null values
    Low          5033  non-null values
    Close        5033  non-null values
    Volume       5033  non-null values
    Adj Close    5033  non-null values
    dtypes: float64(5), int64(1)
    
    In [65]: s
    Out[65]: 
    <class 'pandas.core.frame.DataFrame'>
    Int64Index: 5033 entries, 0 to 5032
    Data columns:
    Date         5033  non-null values
    Open         5033  non-null values
    High         5033  non-null values
    Low          5033  non-null values
    Close        5033  non-null values
    Volume       5033  non-null values
    Adj Close    5033  non-null values
    dtypes: float64(5), int64(1), object(1)
    

    【讨论】:

    • 谢谢安迪,但是,在我使用 inplace=True 后,我收到以下错误“ValueError: invalid literal for float(): 2013-01-23 00:00:00”
    • @user1591487 你用的是什么版本的熊猫? (它在我的机器上运行良好......)
    • 是时候升级了!我不建议使用低于 0.81 的任何值(与当前基于 debian 的发行版一起提供),0.10.1 是当前稳定的(我认为)并且有 0.11 可作为“开发中”
    • 升级到 0.10.0 后,它可以工作,但并不完美,在原始数据帧 t 中,索引是“DatetimeIndex”,但在新数据帧 s 中,索引只是“索引” ,所以当它绘图时,它不会将其视为日期时间。所以我的下一个问题是如何将其设为“DatetimeIndex”?
    • @user1591487 s.index = s.index.to_datetime() :)
    猜你喜欢
    • 2020-01-14
    • 2021-11-25
    • 2015-05-16
    • 1970-01-01
    • 1970-01-01
    • 2017-10-10
    • 2018-11-08
    • 1970-01-01
    • 2014-06-16
    相关资源
    最近更新 更多