2017-08-16 3 views
1

パンダのデータフレームのどのカラムが不連続なデータを持っているかを知りたいと思います。 「不連続」とは、値がある値からゼロに変わったことを意味します。パンダの不連続なデータを見つける方法

[0,0,0,1,2,3,4,5,0,0,0] # continuous 
[0,0,0,1,2,0,4,5,0,0,0] # not continuous 

forループを使用してデータフレームのすべての列を繰り返し処理するコードを実装できました。私は私が何を意味するかを示すために、以下の作業スニペットを作っ:

import numpy as np 
import pandas as pd 

def find_discontinuous(series): 
    switch = 0 
    for index,val in series.iteritems(): 
     # print(val, end=" ") 
     if switch==0 and val==0: 
      # print("still zero") 
      continue 
     elif switch==0 and val!=0: 
      switch = 1 
     if switch==1 and val==0: 
      # print("back to zero") 
      switch = 2 
      continue 
     if switch==2 and val!=0: 
      # print("supposed to be zero") 
      return "not continuous" 
    return "continuous" 

data = np.array([[0,1,2,3,4,5,0], 
       [0,1,2,0,4,5,0]]) 
df = pd.DataFrame(data,columns=list(range(7)),index=list(range(2))).transpose() 

for column in df.columns: 
    series = df.loc[:,column] 
    res = find_discontinuous(series) 
    print(column,res) 

出力:

0 continuous 
1 not continuous 

私はそれとして、パンダのデータフレームを反復するforループを使用し、おそらく正しくないことをどこかで読ん遅い。同じことを達成するためのパンダの道は何でしょうか?

+0

したがって、不連続ではないものはすべて連続していると見なされますか?すべてゼロのような何かは連続的でしょうか? – Divakar

答えて

1

あなただけに必要ゼロからの最初の変化とゼロへの最後の変化との間にゼロがないことを確認してください:

def is_continuous(series): 
    id_first_true = (series > 0).idxmax() 
    id_last_true = (series > 0)[::-1].idxmax() 
    return all((series>0).loc[id_first_true:id_last_true] == True) 
1

あなたはインデックスとContinuousためBoolean値として列名を持つSeriesapplydfを変換することができます。

df.apply(lambda y: not(any(map(lambda x: x[1] == 0 and x[0]>0 and x[2]>0, zip(reversed(y), reversed(y[:-1]), reversed(y[:-2])))))) 

また、あなたがapplyとあなたの機能を使用することができます。

df.apply(find_discontinuous) 
#0  continuous 
#1 not continuous 
関連する問題