ASKSAGE: Sage Q&A Forum - Individual question feedhttps://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Sat, 15 Jun 2013 00:14:37 -0500How do I multiply items within a CSVhttps://ask.sagemath.org/question/10243/how-do-i-multiply-items-within-a-csv/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
prod(mylist)
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:
[['1'],['2'],['3']]
How do I coerce it into the format (1,2,3)?
Fri, 14 Jun 2013 14:29:29 -0500https://ask.sagemath.org/question/10243/how-do-i-multiply-items-within-a-csv/Answer by tmonteil for <p>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:</p>
<pre><code>import csv
mylist = list(csv.reader(open(DATA+'mydata.csv','rb'),dialect='excel'))
from numpy import prod
prod(mylist)
</code></pre>
<p>However, this doesn't work, I receive the following error "TypeError: cannot perform reduce with flexible type".</p>
<p>I think this is because of the format of how the mylist is created. This list data comes out in this format:</p>
<pre><code>[['1'],['2'],['3']]
</code></pre>
<p>How do I coerce it into the format (1,2,3)?</p>
https://ask.sagemath.org/question/10243/how-do-i-multiply-items-within-a-csv/?answer=15086#post-id-15086Here 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])
6
By the way, yo do not have to import the `prod()` function from `numpy`, Sage already have its own.
Sat, 15 Jun 2013 00:14:37 -0500https://ask.sagemath.org/question/10243/how-do-i-multiply-items-within-a-csv/?answer=15086#post-id-15086