2015-01-14 51 views
3

每個CSV列串計數我有一個CSV文件是這樣的:獲取使用Python

Header1,Header2,Header3,Header4 
AA,12,ABCS,A1 
BDDV,34,ABCS,BB2 
ABCS,5666,gf,KK0 

其中一列只能有字母/詞,或只是數字或兩者兼而有之。我有這樣的多個文件,每列中的列不一定相同。我想獲得列中只有字母和數字的每個元素的計數。

我期望的輸出是

Header1- [('AA', 1),('BDDV',1),('ABCS',1)] Header3- [('ABCS', 2),('gf', 1)] 

這裏,雖然雙方的列有「ABCS」,我想分別統計他們的每一列。

我可以通過硬編碼的列數像下面獲取計數:

import csv 
import collections 

count_number = collections.Counter() 
with open('filename.csv') as input_file: 
    r = csv.reader(input_file, delimiter=',') 
    headers = next(r) 
    for row in r: 
     count_number[row[1]] += 1 

print count_number.most_common() 

,但我對如何相對於列做困惑。

+1

只需創建一個計數器列表,其中一列用於您希望計算的每列。 – fnl

回答

1

這可以通過對每個頭一個Counter工作:

#!/usr/bin/env python 
from collections import Counter, defaultdict 
import csv 

header_counter = defaultdict(Counter) 

with open('filename.csv') as input_file: 
    r = csv.reader(input_file, delimiter=',') 
    # read headers 
    headers = next(r) 
    for row in r: 
     # count values for each row to add in header context 
     row_val = sum([w.isdigit() for w in row]) 
     # zip each row with headers to know where to count 
     for header, val in zip(headers, row): 
      # count only non-digits 
      if not any(map(str.isdigit, val)): 
       header_counter[header].update({val: row_val}) 

for k, v in header_counter.iteritems(): 
    print k, v 

輸出:

Header3 Counter({'ABCS': 2, 'gf': 1}) 
Header1 Counter({'AA': 1, 'BDDV': 1, 'ABCS': 1}) 
+0

工作。謝謝! – abn

+1

添加更簡單的代碼來交換'all' +'map' for'any',歡迎您的光臨:) –

1

部分解決方案只(你還需要對您的CSV閱讀器的第二次迭代的數字過濾列)。

import csv 
import collections 

with open('filename.csv') as input_file: 
    r = csv.reader(input_file, delimiter=',') 
    headers = next(r) 
    count_number = [collections.Counter() for I in Len(headers)] 

    for row in r: 
    for i, val in enumerate(row): 
     count_number[i][val] += 1 

print [cr.most_common() for cr in count_number]