Question

I'm new to python and struggling with the function customer_state. I have another function which gets the data from a csv file. I want to get the sum for a column from that file and also get sm1(which gives me growth rate over time t(in days). This is what I have done so far:

def del_pass():
    reader = csv.DictReader(open("data.csv", "rb"))
    all_rows = list()
    for row in reader:
        all_rows.append(row)
    return all rows     

def get_one_column(name):
    column_list= list()
    rows = del_pass()
    for row in rows:
        value  = row(name)
        if value =='':
           value = 0
        else:
           value = int(value)
    column_list.append(value)
    return column_list

def customer_state(x):
    sm = sum(x)
    t = range(366)
    sm1 = sm + (0.07 * (t/365) * sm)
    return sm, sm1

def example_use1():
    column_name ="totcust"
    column = get_one_column(column_name)
    column_stats = customer_state(column)
    print column_stats 

Every functions seems to be working fine except customer_state(x), which gives me the following error.

    sm1 = (sm + ((0.07/t) * sm))
TypeError: unsupported operand type(s) for /: 'float' and 'list'
Was it helpful?

Solution

I'm assuming 0.07 / range(366) should return a list of 0.07 divided by the corresponding element in range(366)?

In that case, you can either use a list comprehension:

sm1 = [sm + ((0.07/t) * sm)) for t in xrange(1,366)]

or, since you applied the numpy-tag to the question, initialize t as a numpy array:

t = numpy.mgrid[1:366]
sm1 = sm + (0.07/t) * sm

then element-wise division will be used as well.

In both cases: mind that indexing and hence the range-list, starts at zero, so the first element in these lists will be Inf.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top