2017-02-16 68 views
0

我是Python新手,需要一些幫助才能獲得調查結果。我有一個CSV文件,它看起來像這樣:CSV文件的Python計數器

Person, Gender, Q1, Q2, Q3 
professor, male, agree, not agree, agree 
professor, male, agree, agree, agree 
professor, female, neutral, not agree, agree 
Professor, female, agree, agree, agree 
student, female, agree, not agree, not agree 
student, female, no answer, not agree, agree 
student, male, no answer, no answer, agree 

我想算每人性別產生不同的答案的次數。例如Q1:(教授,男性:同意,2),(教授,女性:同意1;中性1)等等。 到目前爲止,我已經試過這樣:

import csv 
from collections import Counter 
with open('survey.csv') as csvfile: 
    reader = csv.reader(csvfile, delimiter=',', dialect = csv.excel_tab) 
    counts = Counter(map(tuple,reader)) 
    print [row for row in reader if row] 
    print list(csv.reader(csvfile)) 

但我覺得,因爲我只有串,我沒有得到任何結果。而且,我還不知道如何通過人/性別獲取數據。 非常感謝!

+1

使用['pandas'](http://pandas.pydata.org/pandas-docs/stable/10min.html) – Peter9192

回答

1

使用pandas,你可以這樣做:

import pandas as pd 
my_data = pd.read_csv('survey.csv') 
# To summarize the dataframe for everything together: 
print my_data.describe() 
print my_data.sum() 

# To group by gender, etc. 
my_data.groupby('Gender').count() 
+0

非常感謝。有效! – Carro

+0

非常感謝。我還有一個問題。是否可以使用Groupby.apply獲得所有問題的答案?例如,如果我寫分組= data.groupby(['people','gender'])['Q1','Q2',...]或者還有其他方法可以做到嗎? – Carro

+0

也許有一個遍歷每一個問題的循環? – Carro

0

如果你不想切換到大熊貓,你需要做一些分析,對行,你看他們之後。像下面這樣(未經測試)。這使用Counter對象,其行爲與普通的字典非常相似,除了引用不存在(但不存在)的鍵自動創建並賦予其值0,而不是提高KeyError

from collections import Counter 

counters = [] 
for row in reader: 
    for colno,datum in enumerate(row): 
     if colno >= len(counters): # do we have a counter for this column yet? 
      counters.append(Counter()) # if not, add another Counter 
     counters[colno][datum] += 1 

for counter in counters: 
    print(counter) 

如果您的CSV文件的第一行是一些列標題,您可以提前閱讀它,然後用它來詮釋計數器的列表。如果原材料堆放的櫃檯物品被認爲太難看,我會盡量將櫃檯的內容格式化爲你的練習。