2017-10-17 31 views
0

我正在使用Python熊貓read_excel創建直方圖或線圖。我想閱讀整個文件。這是一個大文件,我只想繪製一些特定的值。我知道如何在read_excel中使用skiprows和parse_cols,但是如果我這樣做,它不會讀取我需要用於軸標籤的文件的一部分。我也不知道如何告訴它繪製我想要的X值和我想要的Y值。繼承人我有什麼:閱讀擅長與Python熊貓和隔離列/行以繪製

df=pd.read_excel('JanRain.xlsx',parse_cols="C:BD") 

years=df[0] 
precip=df[31:32] 
df.plot.bar() 

我想x軸是Excel文件(歲)的第1行,我想在條形圖每個酒吧是在Excel文件的一行31的值。我不知道如何隔離這個。用熊貓閱讀會比較容易,然後用matplotlib繪圖?

這裏是一個excel文件的例子。第一行是年,第二列是該月的天數(該文件僅1個月:

Here is a sample of the excel file. The first row is years and the second column is days of the month (this file is only for 1 month

+1

你有你的Excel電子表格的樣本,你可以發佈? –

回答

3

下面我將如何繪製在一個大的數據幀的行31中的數據,設置行0作爲x軸。(更新回答)

import pandas as pd 
import numpy as np 
import matplotlib.pyplot as plt 
%matplotlib inline 

創建具有32行隨機陣列,和10列

df = pd.DataFrame(np.random.rand(320).reshape(32,10), columns=range(64,74), index=range(1,33)) 
df.to_excel(r"D:\data\data.xlsx") 

只讀列和行的是你想使用「parse_cols」和「skiprows」。這個例子中的第一列是數據框索引。

# load desired columns and rows into a dataframe 
# in this method, I firse make a list of all skipped_rows 
desired_cols = [0] + list(range(2,9)) 
skipped_rows = list(range(1,33)) 
skipped_rows.remove(31) 
df = pd.read_excel(r"D:\data\data.xlsx", index_col=0, parse_cols=desired_cols, skiprows=skipped_rows) 

目前,這會產生一個只有一行的數據幀。

 65  66  67  68  69  70  71 
31 0.310933 0.606858 0.12442 0.988441 0.821966 0.213625 0.254897 

隔離只是你要繪製的行,給予與原列標題pandas.Series作爲索引

ser = df.loc[31, :] 

情節系列。

fig, ax = plt.subplots() 
ser.plot(ax=ax) 
ax.set_xlabel("year") 
ax.set_ylabel("precipitation") 

enter image description here

fig, ax = plt.subplots() 
ser.plot(kind="bar", ax=ax) 
ax.set_xlabel("year") 
ax.set_ylabel("precipitation") 

enter image description here

+0

這有助於y軸!但我文件中的第一行是寫成年份(64 65 66 ... 14 15 16)。我如何獲得X軸來顯示這個?目前它顯示1-37。另外,我不希望有一個傳奇。我只想爲所有酒吧使用相同的顏色。現在寫下我的傳奇正確反映了這些年。我想要將我的圖例中顯示的內容顯示爲x軸。 – Jonathon

+0

我看到你做了什麼index_cols = 0,但我基本上想要使X軸index_rows = 0。我知道index_rows是無效的,但有沒有辦法做到這一點?我想把excel文件的第一行作爲我的x軸 – Jonathon

+0

df.ix [0]會給你第一行。 – patrickjlong1