Ask Your Question

How do I multiply items within a CSV

asked 2013-06-14 21:29:29 +0200

NickC gravatar image

updated 2013-06-14 22:13:24 +0200

Hi, I am trying to import a CSV file then find the product of all of the numbers within the file. The code I have used so far is:

import csv
    mylist = list(csv.reader(open(DATA+'mydata.csv','rb'),dialect='excel'))
    from numpy import prod

However, this doesn't work, I receive the following error "TypeError: cannot perform reduce with flexible type".

I think this is because of the format of how the mylist is created. This list data comes out in this format:


How do I coerce it into the format (1,2,3)?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2013-06-15 07:14:37 +0200

tmonteil gravatar image

updated 2013-06-15 07:23:41 +0200

Here your list is a list of lists (you can see this by the nested brackets), each one contains a single string representing your integer (you can see this by the quotes). You can transform it to a list of integers as follows:

sage: mylist = [['1'],['2'],['3']]
sage: mylist
[['1'], ['2'], ['3']]
sage: [ZZ(i[0])  for i in mylist]
[1, 2, 3]
sage: prod([ZZ(i[0])  for i in mylist])

By the way, yo do not have to import the prod() function from numpy, Sage already have its own.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2013-06-14 21:29:29 +0200

Seen: 282 times

Last updated: Jun 15 '13