2014-09-29 99 views
1

块我有2列的csv文件,代表项目每年分布,看起来像这样:集团通过行25

A  B 

1900 10 
1901 2 
1903 5 
1908 8 
1910 25 
1925 3 
1926 4 
1928 1 
1950 10 

等,约15000线。

根据这些数据制作分布图时,斧头上的点太多了,不太漂亮。我想按照25年的积木来分组,所以最后我会少砍一点。 因此,举例来说,从1900年直到1925年我会在-B柱上生产的物品在A柱的总和,1行1列:

1925 53 
1950 15 

到目前为止,我只能想出如何在CSV数据转换文件为int:

o=open('/dates_dist.csv', 'rU') 
mydata = csv.reader(o) 


def int_wrapper(mydata): 
    for v in reader: 
     yield map(int, v) 

reader = int_wrapper(mydata) 

找不到如何进一步做...

回答

3

你可以使用itertools.groupby

import itertools as IT 
import csv 

def int_wrapper(mydata): 
    for v in mydata: 
     yield map(int, v) 


with open('data', 'rU') as o: 
    mydata = csv.reader(o) 
    header = next(mydata) 
    reader = int_wrapper(mydata) 
    for key, group in IT.groupby(reader, lambda row: (row[0]-1)//25+1): 
     year = key*25 
     total = sum(row[1] for row in group) 
     print(year, total) 

产量

(1900, 10) 
(1925, 43) 
(1950, 15) 

需要注意的是1900年至1925年(含)跨越26年来,如果你希望将25年来,给你所报告的汇总的方式不那么25 ,你可能要半 - 开放时间间隔(1900, 1925]


表达row[0]//25取年和整数25。 该数目除以将是在范围[1900年,1925年)的所有数字是相同的。 要使范围在左侧半开,请减去并加1:(row[0]-1)//25+1

+0

哇,这是快速和完美的!非常感谢:) – user3241376 2014-09-29 12:11:37

+0

@unutbu - 推测'csv.reader'会像这样创建:'csv.reader(o,delimiter ='',skipinitialspace = True)'或类似的东西? (以迎合非标准和可变空间分隔符)。 – mhawke 2014-09-29 12:31:42

+0

@mhawke:是的;由于OP在调用csv.reader的方式上似乎没有问题,因此我没有更改该代码以适应数据的呈现方式。 – unutbu 2014-09-29 13:32:46

0

这是我的方法。它绝对不是最吸引人的Python代码,但可能是实现所需输出的一种方式。

if __name__ == '__main__': 

    o=open('dates_dist.csv', 'rU') 
    lines = o.read().split("\n") # Create a list having each line of the file 

    out_dict = {} 
    curr_date = 0; 
    curr_count = 0 
    chunk_sz = 25; #years 
    if len(lines) > 0: 
     line_split = lines[0].split(",") 
     start_year = int(line_split[0]) 
     curr_count = 0 

     # Iterate over each line of the file 
     for line in lines: 
      # Split at comma to get the year and the count. 
      # line_split[0] will be the year and line_split[1] will be the count. 
      line_split = line.split(",") 
      curr_year = int(line_split[0]) 
      time_delta = curr_year-start_year 

      if time_delta<chunk_sz or time_delta == chunk_sz: 
       curr_count = curr_count + int(line_split[1]) 
      else: 
       out_dict[start_year+chunk_sz] = curr_count 
       start_year = start_year+chunk_sz 
       curr_count = int(line_split[1]) 

      #print curr_year , curr_count  

     out_dict[start_year+chunk_sz] = curr_count 
    print out_dict   
+0

你可以添加一个解释 - 我相信OP会明白这一点。 – 2014-09-29 11:57:46

+0

@BurhanKhalid感谢您指出。已添加内嵌评论... – kundan 2014-09-29 12:07:07

0

你可以做一些整除之后创建一个由它虚拟列和组:

df['temp'] = df['A'] // 25 
>>> df 
     A B temp 
0 1900 10 76 
1 1901 2 76 
2 1903 5 76 
3 1908 8 76 
4 1910 25 76 
5 1925 3 77 
6 1926 4 77 
7 1928 1 77 
8 1950 10 78 

>>> df.groupby('temp').sum() 
     A B 
temp   
76 9522 50 
77 5779 8 
78 1950 10 

我的号码是从你的略有不同,因为我是专门从1900至1924年分组,1925年至1949年和1950-1974年,但这个想法是一样的。