2016-07-13 12 views
0

私はPythonの初心者で、誰かが私を助けてくれるのだろうかと思っていました。Python - pandasデータフレームを介してIterrowし、datetime変数を割り当てて条件付きで更新します。

パンダのデータフレームでdatetime列を反復したいが、反復ごとに最も新しい時刻の変数を更新する。のは、これが私のデータであると仮定しましょう:

Time 
06:12:50 
06:13:51 
06:13:51 
06:13:50 
06:14:51 
06:14:49 

私の結果については、私はそれがこのような何かを見てみたい:

RecentTime: 
    06:12:50 
    06:13:51 
    06:13:51 
    06:13:51 
    06:14:51 
    06:14:51 

私はコードは次のようになりますだと思うが、私はとのトラブルがありましたそれは理由を理解することができません。これは私のコードです:

RecentTime 
    06:12:50 
    06:13:51 
    06:13:51 
    06:13:50 
    06:14:51 
    06:14:49 
+0

通常、 'for'ループを使ってデータフレームを繰り返し処理しないでください。どのように比較し、サブセット化するか、例えば[これらのライン]に沿って考えてみてください(http://stackoverflow.com/questions/32731498/how-to-select-cells-greater-than-a-value-in-a- multi-index-pandas-dataframe) – beroe

答えて

1

あなたは不平等をチェックする前に、変数indexの上に書いているループを通るたびに、そう

if index >= row['Time']: 
:何らかの理由で

RecentTime = [] # Store list of most recent time for each row 
Index: None  # Create empty variable 
# Loop through 
for index, row in data.iterrows(): 
    index = row['Time'] # Save value as index 
    if index >= row['Time']: # If time is greater than current row 
    index = row['Time'] 
     RecentTime.append(index) # Append most recent variable into list 
    else: 
     continue 

、これが私の結果であり、

は常にTrueであるだけでなく、この不等式をチェックする前に常にインデックスを現在の時刻と同じに設定します。望ましい結果に時間が前の行に比べて決して早くないあなたの説明では、パターンに基づいて、私はあなたがより多くのこのような何かを探していると思う:

RecentTime = [] # Store list of most recent time for each row 
priortime = None 
# Loop through 
for index, row in data.iterrows(): 
    currenttime = row['Time'] 
    if priortime is None: 
     priortime = currenttime 

    if priortime > currenttime: # If prior time is greater than current row 
     currenttime = priortime 

    priortime = currenttime  
    RecentTime.append(currenttime) 

最後に、ラインIndex: Noneがエラーをスローする必要がありますSyntaxError: invalid syntax。変数に値を代入する場合は、Index = Noneを使用します。 index(小文字)は、データフレームのインデックス値を参照するためにデータフレームループで既に使用されています。したがって、大文字のIndex変数が競合しなくても、別の名前を付けてください。

+0

最新の 'currenttime'の60秒の時間差内にある行を保持するための引数を含めることは可能ですか? – ClarityParity

+0

はい、datetime.timedeltaを使用できます。 – Michael

関連する問題