CSVデータにX座標Y座標として駅の座標があります。
一番最初の座標から次の座標までの距離、またその次の座標までの距離をすべて足して出力したいです。
numpyを使用しないバージョンでは下記参照コードでなんとかできましたが、numpy使用バージョンで、もっとnumpyの特性というか。for文等をあまり使わないでコード記述してみたいのですが、なかなか思いつかなくて・・アドバイスお願いします。
CSV
10.6202894507523649,-4.732210337179897 27.662316204642959,-7.393462117282397 3-9.000860650190178,5.386582472630646 4-8.902462874913837,-0.27987478404612354 5-9.391803940946751,8.422614695955076 6-6.749908626465608,-1.3866296185366522 75.498584173099712,0.437729343757562 80.4031336912750447,8.633667135803336 9-0.5490371265038174,3.9540065878930992 10-2.7653221752486274,6.519722752462222 11-0.7064688142175655,-3.371742089032077 122.324605901134067,-8.180587545724764 13~略(1000件くらいのデータがあります。)~
python
1numpyライブラリ使用しないバージョン 2#平方根の計算のためmathライブラリをインポート 3import math 4 5f = open("test1018.csv") 6a = [] 7b = [] 8c = [] 9 10#CSVを読み込む 11for s in f: 12 13 a.append(s.split(',')) 14#print(a) 15 16 17a_l = len(a) 18#print(a_l) 19 20 21#列ごとにリストを作成 22for i in range(2): 23 for j in range(a_l): 24 if i == 0: 25 26 b.append(a[j][i]) 27 28 elif i == 1: 29 c.append(a[j][i]) 30 31 32#print(b) 33#print(c) 34 35#改行を取り除く 36d = [] 37for s in c: 38 p = s.strip("\n") 39 40 41 d.append(p) 42 43 44 45#数値にする 46b = [float(h) for h in b] 47#print("B",b) 48 49d = [float(n) for n in d] 50 51 52 53X = 0 54Y = 0 55total = 0 56#zipにする 57for g,h in zip(b,d): 58 59 if X == 0: 60 X = g 61 Y = h 62 63 else: 64 T = math.sqrt((X - g) ** 2 + (Y - h) ** 2) 65 total += T 66 67 68 69print(total)
python
1numpy使用バージョン 2#ライブラリのインポート 3import pandas as pd 4import numpy as np 5import math 6 7 8#pandas でcsvデータを読み込む タイトルがないのでheader = Noneを引数に追加 9station = pd.read_csv("test1018.csv",header=None) 10#print(station) 11#print(type(station)) 12 13 14#配列に変換する 15nd_station = station.values 16#print(nd_station) 17 18 19 20#座標の距離を求めて合計に追加 21X = 0 22Y = 0 23total = 0 24for i , j in nd_station: 25 26 if X == 0: 27 X = i 28 Y = j 29 30 else: 31 t = math.sqrt((X - i) ** 2 + (Y - j) ** 2) 32 total += t 33 34#結果出力 35print(total)
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/10/20 03:49
2018/10/20 04:02
2018/10/20 04:05