質問編集履歴
1
改良後のソースコードを追加
test
CHANGED
File without changes
|
test
CHANGED
@@ -189,3 +189,109 @@
|
|
189
189
|
|
190
190
|
|
191
191
|
Python初めて2日程度なので、Pythonらしく直していただいて構いません。
|
192
|
+
|
193
|
+
|
194
|
+
|
195
|
+
### 改良後のソースコード
|
196
|
+
|
197
|
+
lehshellさんから改良案を頂き、そのあたりで自分で調べた結果もふまえて書き換えたコードを以下においておきます。
|
198
|
+
|
199
|
+
shiftメソッドの他に、diffでもできるみたいです。
|
200
|
+
|
201
|
+
|
202
|
+
|
203
|
+
|
204
|
+
|
205
|
+
```Python
|
206
|
+
|
207
|
+
import pandas as pd
|
208
|
+
|
209
|
+
|
210
|
+
|
211
|
+
def length(pos1,pos2):
|
212
|
+
|
213
|
+
ans = ((pos1.x - pos2.x) **2 + (pos1.y - pos2.y) **2 + (pos1.z - pos2.z) **2)** 0.5
|
214
|
+
|
215
|
+
return ans
|
216
|
+
|
217
|
+
|
218
|
+
|
219
|
+
def length2(diffx,diffy,diffz):
|
220
|
+
|
221
|
+
ans = (diffx ** 2 + diffy ** 2 + diffz ** 2) ** 0.5
|
222
|
+
|
223
|
+
return ans
|
224
|
+
|
225
|
+
|
226
|
+
|
227
|
+
def method1(): #改良前
|
228
|
+
|
229
|
+
df = pd.read_excel('test2.xlsx')
|
230
|
+
|
231
|
+
lastvar = 0
|
232
|
+
|
233
|
+
df['df_time'] = 0
|
234
|
+
|
235
|
+
df['len'] = 0.0
|
236
|
+
|
237
|
+
df['spd'] = 0.0
|
238
|
+
|
239
|
+
|
240
|
+
|
241
|
+
for item in df.itertuples():
|
242
|
+
|
243
|
+
if (hasattr(lastvar, 'Time')):
|
244
|
+
|
245
|
+
diff = item.Time - lastvar.Time
|
246
|
+
|
247
|
+
len = length(item,lastvar)
|
248
|
+
|
249
|
+
df.at[item.Index, 'df_time'] = diff
|
250
|
+
|
251
|
+
df.at[item.Index, 'len'] = len
|
252
|
+
|
253
|
+
df.at[item.Index, 'spd'] = len / diff * 1000
|
254
|
+
|
255
|
+
lastvar = item
|
256
|
+
|
257
|
+
print(df)
|
258
|
+
|
259
|
+
|
260
|
+
|
261
|
+
def method2(): #改良案1
|
262
|
+
|
263
|
+
df = pd.read_excel('test2.xlsx')
|
264
|
+
|
265
|
+
df['df_time'] = (df['Time'] - df['Time'].shift(1)).fillna(0)
|
266
|
+
|
267
|
+
df['len'] = length(df, df.shift(1)).fillna(0)
|
268
|
+
|
269
|
+
df['spd'] = (df['len'] / df['df_time'] * 1000).fillna(0)
|
270
|
+
|
271
|
+
print(df)
|
272
|
+
|
273
|
+
|
274
|
+
|
275
|
+
def method3(): #改良案2
|
276
|
+
|
277
|
+
df = pd.read_excel('test2.xlsx')
|
278
|
+
|
279
|
+
df['df_time'] = df['Time'].diff().fillna(0)
|
280
|
+
|
281
|
+
df['len'] = length2(df["x"].diff(),df["y"].diff(),df["z"].diff()).fillna(0)
|
282
|
+
|
283
|
+
df['spd'] = (df['len'] / df['df_time'] * 1000).fillna(0)
|
284
|
+
|
285
|
+
print(df)
|
286
|
+
|
287
|
+
|
288
|
+
|
289
|
+
|
290
|
+
|
291
|
+
method1()
|
292
|
+
|
293
|
+
method2()
|
294
|
+
|
295
|
+
method3()
|
296
|
+
|
297
|
+
```
|