2017-10-17 94 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