我是matplotlib的新手,需要一些指导。我试图从“Pandas DataFrame中的烛台图”中重现此代码,作为通过添加“read_csv”函数来学习的方法。
我的错误信息一直说“valueError:长度不匹配:预期的轴有6个元素,新值有5个元素”
我的问题是:
请帮忙。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
from mpl_finance import candlestick_ohlc
import matplotlib.dates as mdates
import datetime as dt
df = pd.read_csv("/Users/paul/Documents/python (original)/Quant/sp500.csv", usecols=['Date', 'Open','High','Low','Close'])
#Reset the index to remove Date column from index
df_ohlc = df.reset_index()
#Naming columns
df_ohlc.columns = ["Date","Open","High",'Low',"Close"]
#Converting dates column to float values
df_ohlc['Date'] = df_ohlc['Date'].map(mdates.date2num)
#Making plot
fig = plt.figure()
ax1 = plt.subplot2grid((6,1), (0,0), rowspan=6, colspan=1)
#Converts raw mdate numbers to dates
ax1.xaxis_date()
plt.xlabel("Date")
print(df_ohlc)
#Making candlestick plot
candlestick_ohlc(ax1,df_ohlc.values,width=1, colorup='g', colordown='k',alpha=0.75)
plt.ylabel("Price")
plt.legend()
plt.show()
答案 0 :(得分:2)
你不需要" 0"," 1"," 2"在.csv文件中的每一行之前。您必须首先删除它,然后:
如果您要重置索引,则需要在数据框中添加实际索引列,因此请添加index_col
,如下所示:
df = pd.read_csv("/Users/paul/Documents/python (original)/Quant/sp500.csv", usecols=['Date', 'Open','High','Low','Close'], index_col= 'Date')
将日期列从字符串转换为日期时间:
df_ohlc['Date'] = pd.to_datetime(df_ohlc['Date'])
编辑:
如果您不能删除csv文件中的0,1,2 ...列,因为它太大,请修改第一行以使'索引'列如下所示:
'index', 'Date', 'Open','High','Low','Close'
然后,在您的代码中:
df = pd.read_csv("/Users/paul/Documents/python (original)/Quant/sp500.csv", usecols=['index', 'Date', 'Open','High','Low','Close'], index_col="Date")
df.drop('index', axis=1, inplace=True)