2017-01-16 1 views
-3

파이썬에 초보자가 생겼습니다. 질문이 있습니다. CSV 파일에서 데이터를로드하고 중복을 제거하고 제거 된 CSV 파일을 저장 한 다음 올바른 CSV 파일을로드하고 그래프를 생성합니다. 그러나 내 문제는 합계가 잘못되어 그래프가 올바르게 표시되지 않는다는 것입니다. 나는 프로그램이 제대로 작동하는지 알기 때문에 섹션 1을 제거하면 (아래 섹션 # 1 참조) 정확한 데이터가 표시됩니다. 제 1 절에서 무엇이 데이터를 비뚤어지게하는지 알 수 없습니다 ... 어떤 도움이라도 대단히 감사하겠습니다. 감사.파이썬 - 데이터가 올바르게 표시되지 않습니다. (Matplotlib)

요약 : 동일한 py 파일에서 섹션 1과 섹션 2를 실행할 수 없습니다. 그렇지 않으면 데이터의 집계가 잘못됩니다. 이유를 알고 싶습니까? 별도의 py 파일을 실행하지 않고 피하는 방법.

from collections import Counter 
import numpy as np 
import matplotlib 
import matplotlib.pyplot as plt 
import pandas as pd 
import csv 
import itertools 

제 1

# Create database of duplicates - check if the mac and os pairs have  duplicates 
reader = csv.reader(open('Workbook1.csv', 'r'), delimiter=',') 
writer = csv.writer(open('remacos.csv', 'w'), delimiter=',') 
entries = set() 

for row in reader: 
key = (row[1], row[2]) 

if key not in entries: 
    writer.writerow(row) 
    entries.add(key) 

entries.clear() 
# Create database of duplicates - check if the mac and browser pairs  have duplicates 
reader = csv.reader(open('Workbook1.csv', 'r'), delimiter=',')  
writer = csv.writer(open('remacbrowser.csv', 'w'), delimiter=',') 
entries = set() 

for row in reader: 
key = (row[1], row[3]) 

if key not in entries: 
    writer.writerow(row) 
    entries.add(key) 
# Read Removed Duplicated entries Database and Count Values for OS. 
df = pd.read_csv('remacos.csv', index_col="mac")   
counteros = Counter(df['os']) 
os_names = counteros.keys() 
os_counts = counteros.values() 

# Read Removed Duplicated entries Database and Count Values for  Browsers. 
df = pd.read_csv('remacbrowser.csv', index_col="mac")   
counterbrowsers = Counter(df['browser']) 
browser_names = counterbrowsers.keys() 
browser_counts = counterbrowsers.values() 

2 막대 그래프를 생성 장 및

# Plot histogram using matplotlib bar() for OS. 
indexes = np.arange(len(os_names)) 
width = 0.7 
plt.bar(indexes, os_counts, width) 
plt.xticks(indexes + width * 0.5, os_names) 
plt.show() 

# Plot histogram using matplotlib bar() for Browsers. 
indexes = np.arange(len(browser_names)) 
width = 0.7 
plt.bar(indexes, browser_counts, width) 
plt.xticks(indexes + width * 0.5, browser_names) 
plt.show() 

# Make Pie Chart for OS's 
plt.figure() 
values = os_counts 
labels = os_names 
def make_autopct(values): 
def my_autopct(pct): 
total = sum(values) 
val = int(round(pct*total/100.0)) 
return '{p:.2f}% ({v:d})'.format(p=pct,v=val) 
return my_autopct 
plt.pie(values, labels=labels, autopct=make_autopct(values)) 
#plt.pie(values, labels=labels) #autopct?? 
plt.show() 
# Make Pie Chart for Browsers 
plt.figure() 
values = browser_counts 
labels = browser_names 
def make_autopct(values): 
def my_autopct(pct): 
total = sum(values) 
val = int(round(pct*total/100.0)) 
return '{p:.2f}% ({v:d})'.format(p=pct,v=val) 
return my_autopct 
plt.pie(values, labels=labels, autopct=make_autopct(values)) 
#plt.pie(values, labels=labels) #autopct?? 
plt.show()' 
+1

"그래프가 올바르게 표시되지 않습니다"는 충분한 문제 설명이 아닙니다. 원래 파일을 사용할 때 플로팅이 잘 작동한다고 말하는 것처럼이 문제는 "section1"과 관련되어 있으므로 "section2"모두이 질문에 쓸모가 없습니다. 대신 csv 파일에서 두 개의 데이터 행만 사용하여 [MCVE]를 만들어보십시오. "section1"의 결과를 기대했던 것과 비교해보십시오. 또한, 당신이 질문에 무엇을 기대하는지 명시하고 for-loops에서 들여 쓰기를 위의 코드를 수정하십시오. – ImportanceOfBeingErnest

+0

이 모든 것은 완전한 프로그램입니다. 제가 말하고자하는 것은 .py 파일에서 섹션 1을 제거하면 그래프에 정확한 카운트가 표시됩니다. 섹션 1을 포함 시키면 의미가있는 경우 더 낮은 카운트를 얻습니다. 예를 들어, 원형 차트의 displayd가 221이지만 올바른 그림이 240 인 경우 HandHeld 브라우저의 카운트. 스크립트에서 섹션 1을 제거하지만 ID가 하나의 스크립트에서 모두 같으면 올바른 수치를 얻습니다. 그래서 몇 가지 이유로 섹션 1이 카운트를 왜곡하고 있습니다. – user2273231

답변

-1

솔루션은 각 writer'after '델을 추가했다 원형 차트 중복 데이터베이스 만들기

관련 문제