Python: Aggregate data for different users on different days
Question: I'm a new Python user and learning how to manipulate/aggregate data.

I have some sample data of the format:

    
    
    User Date      Price
    A    20130101   50
    A    20130102    20
    A    20130103    30
    B    20130201    40
    B    20130202    20
    

and so on.

I'm looking for some aggregates around each user and expecting an output for
mean spend like:

    
    
    User  Mean_Spend
    A      33
    B      30
    

I could read line by line and get aggregates for one user but I'm struggling
to read the data for different users.

Any suggestions highly appreciated around how to read the file for different
users.

Thanks


Answer: The collections have a `Counter` object
([documentation](https://docs.python.org/2/library/collections.html#counter-
objects)) based off of `Dictionary` that's meant for this kind of quick
summation. Naively, you could use one to accumulate the spend amounts, and
another to tally the number of transactions, and then divide.

    
    
    from collections import Counter
    accumulator =  Counter()
    transactions = Counter()
    
    # assuming your input is exactly as shown...
    with open('my_foo.txt', 'r') as f:
        f.readline() # skip header line
        for line in f.readlines():
            parts = line.split()
            transactions[parts[0]] += 1
            accumulator[parts[0]]+=int(parts[2])
    
    result = dict((k, float(accumulator[k])/transactions[k]) for k in transactions)
    

