熊猫:绘制DataFrame

时间:2018-12-01 21:28:35

标签: python pandas dataframe plot multi-index

我正在绘制以下熊猫MultiIndex DataFrame:

print(log_returns_weekly.head())

           AAPL      MSFT      TSLA        FB     GOOGL
Date Date                                                  
2016 1    -0.079078  0.005278 -0.155689  0.093245  0.002512
     2    -0.001288 -0.072344  0.003811 -0.048291 -0.059711
     3     0.119746  0.082036  0.179948  0.064994  0.061744
     4    -0.150731 -0.102087  0.046722  0.030044 -0.074852
     5     0.069314  0.067842 -0.075598  0.010407  0.056264

,第一个子索引代表年份,第二个子索引代表特定年份的一周。

这可以通过pandas plot()方法简单地实现;但是,如下图所示,x轴将不是(年,周)格式,即(2016,1),(2016,2)等。相反,它仅显示“ Date,Date”-因此有人知道吗我该如何克服这个问题?

log_returns_weekly.plot(figsize(8,8))

enter image description here

1 个答案:

答案 0 :(得分:0)

您需要将多索引转换为单索引并添加一天,因此就像这样:2016-01-01

log1 = log_returns_weekly.set_index(log_returns_weekly.index.map(lambda x: pd.datetime(*x,1)))
log1.plot()