2017-04-24 6 views
0

배경 : 다양한 실험 작업을위한 데이터를 분석하는 중입니다. 목표는 다양한 시트를 사용하여 Excel 파일을 가져 오는 것입니다. 그런 다음 데이터에서 노이즈를 "필터링"하고 모든 샘플의 평균을 찾습니다. 그런 다음 그래프를 플롯하고 그래프를 저장하십시오.Python : df.mean이 잘못된 출력을주는 것 같습니다. 이유가 무엇입니까?

PROGRESS & 문제 : 나는 모든 언급 한 단계를 수행 할 수 있었다 그러나, 평균 VS 다양한 샘플 최종 그래프는 그 나에게 잘못 보인다. 나는 "df.mean"이 평균을 찾는 올바른 방법인지 아닌지 잘 모르겠습니다. 내가 얻은 그래프를 첨부했는데 어떻게 든 평균이 그렇게 낮을 수 있다는 것에 동의 할 수없는 것입니까? It can be seen that the saved image from my code cuts off the legend, how can I change this?

개선 필요 : 이 유래 내 첫 번째 질문 내가 파이썬 여전히 새로운입니다. 코드는 매우 "푹신 푹신한"것처럼 보입니다. 코드 단축에 대한 제안이 있으면 감사하겠습니다.

MY CODE : 코드에서 반복 대부분의

#IMPORT LIBRARIES 
import pandas as pd 
import numpy as np 
import matplotlib.pyplot as plt 

#IMPORT DATA 
excel_df= pd.ExcelFile('data.xlsx',delimiter = ';') #import entire excel file 
sheet1=pd.read_excel('data.xlsx',sheetname=0,names=['time','void1','pressure1']) 
sheet2=pd.read_excel('data.xlsx',sheetname=1,names=['time','void2','pressure2']) 
sheet3=pd.read_excel('data.xlsx',sheetname=2,names=['time','void3','pressure3']) 
sheet4=pd.read_excel('data.xlsx',sheetname=3,names=['time','void4','pressure4']) 
sheet5=pd.read_excel('data.xlsx',sheetname=4,names=['time','void5','pressure5']) 
sheet6=pd.read_excel('data.xlsx',sheetname=5,names=['time','void6','pressure6']) 
sheet7=pd.read_excel('data.xlsx',sheetname=6,names=['time','void7','pressure7']) 
sheet8=pd.read_excel('data.xlsx',sheetname=7,names=['time','void8','pressure8']) 
sheet10=pd.read_excel('data.xlsx',sheetname=9,names=['time','void10','pressure10']) 

#SORT VALUES TO FIND THE UNWANTED DATA 
sheet1.sort_values('pressure1',ascending=False).head() #the pressure has noise so sort accordingly 

#GET ONLY WANTED DATA WITHOUT NOISE 
sheet1_new = sheet1[sheet1.pressure1 <=8] #exclude the noise above 8 bar 
sheet2_new = sheet2[sheet2.pressure2 <=8] #exclude the noise above 8 bar 
sheet3_new= sheet3[sheet3.pressure3 <=8] #exclude the noise above 8 bar 
sheet4_new = sheet4[sheet4.pressure4 <=8] #exclude the noise above 8 bar 
sheet5_new = sheet5[sheet5.pressure5 <=8] #exclude the noise above 8 bar 
sheet6_new = sheet6[sheet6.pressure6 <=8] #exclude the noise above 8 bar 
sheet7_new = sheet7[sheet7.pressure7 <=8] #exclude the noise above 8 bar 
sheet8_new = sheet8[sheet8.pressure8 <=8] #exclude the noise above 8 bar 
sheet10_new = sheet10[sheet10.pressure10 <=8] #exclude the noise above 8 bar 

#MERGE THE DATASETS TO FIND AVERAGE OF ALL SAMPLES 

#'MERGE' ONLY MERGES 2 DATAFRAMES AT A TIME 
merge12_df = pd.merge(sheet1_new,sheet2_new, on='time') 
merge34_df = pd.merge(sheet3_new,sheet4_new, on='time') 
merge56_df = pd.merge(sheet5_new,sheet6_new, on='time') 
merge78_df = pd.merge(sheet7_new,sheet8_new, on='time') 

#MERGE ON FIRST OUTPUT 
all_merged = merge12_df.merge(merge34_df, on='time').merge(merge56_df, on = 'time').merge(merge78_df, on = 'time').merge(sheet10_new, on = 'time') 
#print(all_merged.head()) #check that all data is merged into one dataframe 

#AVERAGE ALL PRESSURES 
mean_all_pressures = all_merged[["pressure1", "pressure2","pressure3", "pressure4","pressure5", "pressure6","pressure7", "pressure8", "pressure10"]].mean(axis=1) 

#PRINT AVERAGE VS ALL THE SAMPLES GRAPH 
plt.figure(1) 
plt.plot(all_merged.time,mean_all_pressures,'r.') #plot the average of all samples. 
plt.plot(sheet1_new.time,sheet1_new.pressure1) 
plt.plot(sheet2_new.time,sheet2_new.pressure2) 
plt.plot(sheet3_new.time,sheet3_new.pressure3) 
plt.plot(sheet4_new.time,sheet4_new.pressure4) 
plt.plot(sheet5_new.time,sheet5_new.pressure5) 
plt.plot(sheet6_new.time,sheet6_new.pressure6) 
plt.plot(sheet7_new.time,sheet7_new.pressure7) 
plt.plot(sheet8_new.time,sheet8_new.pressure8) 
plt.plot(sheet10_new.time,sheet10_new.pressure10) 
plt.legend(['Average','Sample 1','Sample 2','Sample 3','Sample 4','Sample 5','Sample 6','Sample 7','Sample 8','Sample 10'],bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) 
plt.xlabel('Time (s)'),plt.ylabel('Pressure (bar)') #Specify the plot details 
plt.savefig('AllPressures_vs_Average.png') #Save the plot for later use 
plt.show() #Display the plot 
+3

'범위의 납입을 위해 (1,11)은'여기에 코드를 많이 절약 할 수 ... –

+0

평균은 그래프에서 빨간색 점이다. 내 첫 이미지가 올바르게 업로드되지 않았습니다. –

+0

건전성은 명시 적으로 계산을 명시 적으로 수행하여 평균값을 확인합니다. 즉, 필터링 된 압력 값을 나눈 값과 나눗셈 대신 샘플 번호를 합산합니다. – DrBwts

답변

0

은 각 시트에 대해 별도의 변수를 정의하고 이들 각각에 동일한 작업을 수행한다는 사실에서 비롯됩니다.

별도의 변수가 아닌 각 시트의 내용을 단일 사전에 저장하여 현재 코드를 향상시킬 수 있습니다.

documentation에서 s heetname = None을 지정하면 모든 시트를 사전으로 가져올 수 있습니다. 또는 0- 색인으로 된 [0,1,2,...,11]의 사례에서 읽을 시트 목록을 제공 할 수 있습니다. 당신이 필요로 할 때

for name, sheet in sheets_dict.iteritems(): 
    print name, sheet.head() 

당신은 개별적으로 각각의 시트에 액세스 할 수 있습니다 :

sheets_dict['sheet_1_name'] 

을 그리고 이것은 많은 반복을 피할 것

sheets_dict = pd.read_excel('data.xlsx',sheetname=None,names=['time','void1','pressure1']) 

빠르게 사용 것을 볼 수 있습니다. 예를 들어, 필터링은 단순히 다음과 같습니다

new_sheets_dict = {key: el[el.pressure1 <=8] for key, el in sheets_dict.iteritems)}