2

i am using Numpy in python to read a csv file:

import numpy as np
import csv
from StringIO import StringIO
with open ('1250_12.csv','rb') as csvfile:
    data = np.genfromtxt(csvfile, dtype = None, delimiter = ',')
np.set_printoptions(threshold='nan'

which prints out the following:

[['x1' 'y1' 'z1' 'x2' 'y2' 'z2' 'cost']
 ['5720.44' '3070.94' '2642.19' '5797.82' '3061.01' '2576.29' '102.12']
 ['5720.44' '3070.94' '2642.19' '5809.75' '3023.6' '2597.81' '110.4']
 ['5861.54' '3029.08' '2742.36' '5981.23' '3021.52' '2720.47' '121.92']
 ['5861.54' '3029.08' '2742.36' '5955.36' '3012.95' '2686.28' '110.49']

so the first column belongs to 'x1', second column belongs to 'x2'...etc. Lets say x1,y1,z1 is a vector represented in an array and the points underneath represents the value. As you can see there are mulitple points for each x1,y1...etc. Now i want to add up the points so that it becomes the sum of the vectors using an iterator. How do i use an iterator to sum up all the rows?

like this:

import numpy
a=numpy.array([0,1,2])
b=numpy.array([3,4,5])
a+b
array([3, 5, 7])

but this is only 2 arrays, what if there are hundreds then you would need an iterator instead of manually setting the arrays right?

4

3 に答える 3

5

最初の行をスキップしてインポートしないのはなぜですか?

data = np.genfromtxt('1250_12.csv', delimiter = ',', skip_header=1)

それから

np.sum(data,axis=0)
于 2013-08-02T16:35:48.440 に答える
1

他の人がコメントしているように、組み込み関数でこれを行う方法はおそらくありますが、説明したとおりに次のように実行します。

sum = np.zeros(len(data[0]))

for vector in data[1:]:
    vector = map(float, vector)
    sum = np.add(vector, sum)

まず、sumデータ行列の幅に等しい空白ベクトルを初期化します。次に、実際のデータ ベクトルを繰り返し処理し、合計します。

于 2013-08-02T16:32:44.910 に答える
0

Pythonでこれを行いたい場合、方法の1つはリストを反復することです。入力、つまり配列のリストがinpで、出力配列が合計で格納されていると仮定しましょう

total = inp[1]
for eachRow in inp[2:]:
    for index, val in enumerate(eachRow):
        total[index] += eachRow[index]

お役に立てれば :)

于 2013-08-02T16:49:16.880 に答える