2016-09-27 78 views
1

我試圖從Excel電子表格中提取數據,然後在相鄰行之間找到百分比變化。我想要進行這種操作的列是第1列和第4列。然後,我想要使用第0列作爲x軸的子圖,在兩個不同的條形圖中繪製這些百分比變化。
我能夠完成除提取數據和制定相鄰行之間的百分比變化之外的任何操作。百分比變化的公式是Current/previous-1或(r,0)/(r-1,0)-1。下面是我當前的腳本:python,xlrd:使用xlrd函數處理電子表格數據,然後繪製操縱數據圖形

import xlrd 
import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.ticker as tkr 
import matplotlib.dates as mdates 
import datetime 
from matplotlib import rc 
rc('mathtext', default='regular') 

file_location = "/Users/adampatel/Desktop/psw01.xls" 
workbook = xlrd.open_workbook(file_location, on_demand = False) 
worksheet = workbook.sheet_by_name('Data 1') 

x = [worksheet.cell_value(i+1699, 0) for i in range(worksheet.nrows-1699)] 
y1 = [worksheet.cell_value(i+1699, 1) for i in range(worksheet.nrows-1699)] 
y2 = [worksheet.cell_value(i+1699, 4) for i in range(worksheet.nrows-1699)] 

fig = plt.figure() 
ax1 = fig.add_subplot(211) 
ax2 = fig.add_subplot(212, sharex = ax1) 

start_date = datetime.date(1899, 12, 30) 
dates=[start_date + datetime.timedelta(xval) for xval in x] 
ax1.xaxis.set_major_locator(mdates.MonthLocator((), bymonthday=1,  interval=2)) 
ax1.xaxis.set_minor_locator(mdates.MonthLocator((), bymonthday=1, interval=1)) 
ax1.xaxis.set_major_formatter(mdates.DateFormatter("%b'%y")) 

ly1 = ax1.bar(dates, y1, 0.9) 
ly2 = ax2.bar(dates, y2, 0.9) 

ax1.grid() 
ax2.grid() 
ax1.set_ylim(-3,3) 
ax2.set_ylim(-3,3) 

fig.text(0.5, 0.04, 'Inventory Weekly Percent Change', ha='center', va='center', size = '14') 
fig.text(0.06, 0.5, 'Weekly Percent Change', ha='center', va='center', size = '14', rotation='vertical') 

ax1.set_title('Oil', size = '12') 
ax2.set_title('Gasoline', size = '12') 

plt.savefig('Gasoline Inventories Weekly Percent Change.png', bbox_inches='tight', dpi=300) 
plt.show() 

回答

0

給定的值的列表:

y1 = [1000,1010,950,1050,1100,1030] 

純Python的解決方案:

使用zip函數創建的分子和分母的元組。然後使用列表理解來獲取百分比變化的列表。

pct_chg = [1.0*num/den - 1 for num, den in zip(y1[1:], y1)] 

numpy的溶液:

轉換列表以numpy的陣列,然後用切片陣列執行計算。

a1 = np.array(y1) 
pct_chg = np.divide(a1[1:],a1[:-1])-1 

熊貓一攬子解決方案:

轉換列表,熊貓系列,並使用內置的百分比變化功能

s1 = pd.Series(y1) 
pct_chg = s1.pct_change() 

現在,pct_chg是一個系列了。你可以通過pct_chg.values得到它的數值在一個numpy數組中。在大多數情況下,Matplotlib應該接受numpy數組作爲容器。