2017-04-03 8 views
-4

私は2つの列を持つcsvファイルを持っています。最初は人のIDで、もう1つは速度です。私はすべてのIDの平均速度を求めます。csvファイルの列の速度を計算する方法は?

私のcsvファイルは次のようになります。

0001;12 
0001;0.14 
0001;96 
0002;19 
0002;20 
0002;6.3 
0003;25 
0003;1.9 
0003;16 

私はPythonで初心者ですし、本当に多くのPythonのトリックを知りません。私が知っていることは、多分私のコードをあまりに複雑にすることです。

+2

多分ここから:[13.1。 csv - CSVファイルの読み込みと書き込み](https://docs.python.org/2/library/csv.html) –

+1

複雑なコードはどこですか?どのバージョンのPythonを使用していますか? – martineau

+0

私はPython 3.5を使用しています –

答えて

1

ここでは、ファイルからデータを読み取る方法は次のとおりです。

import csv 
from pprint import pprint 

filename = 'velocities.csv' 

# read user velocities from file into a dictionary of lists 
user_velocities = {} 
with open(filename, newline='') as csvfile: 
    for user_id, velocity in csv.reader(csvfile, delimiter=';'): 
     user_velocities.setdefault(user_id, []).append(float(velocity)) 

print('User velocities read from file:', filename) 
pprint(user_velocities) 

は出力:

User velocities read from file: velocities.csv 
{'0001': [12.0, 0.14, 96.0], 
'0002': [19.0, 20.0, 6.3], 
'0003': [25.0, 1.9, 16.0]} 

あなたは、各ユーザーIDの平均速度を計算する方法を把握するためにそれが今簡単にする必要がありますそれぞれに関連付けられた値のリストからuser_velocities辞書を削除します。

(ヒント:。sum()を内蔵しており、len()関数を使用)

+0

多くのありがとうございました –

関連する問題