2016-12-06 16 views
1

私はxで単調なパンダデータフレームを作るための高速な方法を探しています。pandas.Seriesを単調にする簡単な方法はありますか?

def make_monotonic(df, cols=None): 
    """make df monotonic""" 
    if not cols: 
     cols = df.columns 

    mycol = "_maximum" 

    dfm = df.copy() 
    for col in cols: 
     dfm[mycol] = np.maximum.accumulate(dfm[col]) 
     dfm.drop_duplicates([mycol], keep="first", inplace=True) 
    del dfm[mycol] 
    return dfm 

n=21 
np.random.seed(21) 
x = np.linspace(0,np.pi,n) 
dx = .5 * (np.random.random(n)-.5) 
df = pd.DataFrame.from_dict({"x0":x, "x":x+dx, "y":np.sin(x)}) 
dfm = make_monotonic(df, cols=["x"]) 

Make colum x monotonic in "x" Make colum x monotonic in "x"

は、I(x)は

  x   x0    y 
0 -0.676913 0.000000 0.000000e+00 
1 -0.002176 0.314159 3.090170e-01 
2 0.959768 0.628319 5.877853e-01 
3 0.224902 0.942478 8.090170e-01 
4 0.815521 1.256637 9.510565e-01 
5 0.896956 1.570796 1.000000e+00 
6 1.588363 1.884956 9.510565e-01 
7 2.444980 2.199115 8.090170e-01 
8 2.225446 2.513274 5.877853e-01 
9 2.952820 2.827433 3.090170e-01 
10 2.495949 3.141593 1.224647e-16 

  x   x0   y 
0 -0.676913 0.000000 0.000000 
1 -0.002176 0.314159 0.309017 
2 0.959768 0.628319 0.587785 
6 1.588363 1.884956 0.951057 
7 2.444980 2.199115 0.809017 
9 2.952820 2.827433 0.309017 
に関数y = Fを生成したい:

私の現在のソリューションは、以下のとおりです。

+0

シリーズが単調に単調であるとはどういう意味ですか? –

+0

"単調なx"は、各行のx値が常に前の行のx値より大きくなるようにすることを意味します。 – steller

+0

データを並べ替えるだけでいいのですか? –

答えて

1

実際には、df.cummax()でこれを行う非常に簡単な方法です。

cols = ['your', 'columns'] 
mon_inc = (df[cols].cummax().diff().fillna(.1) > 0).all(axis=1) 
df[mon_inc] 

下記古いロジック:すべての値が0

while True: 
    mon_inc = df['x'].diff().fillna(0) >= 0 
    if mon_inc.all(): 
     break 
    df = df[mon_inc] 

そして、任意の数の操作を行うための機能よりも大きくなるまで

あなたはdiffメソッドを使用して行に差分を取る保つことができます列

def make_monotonic(df, cols=None): 
    if cols is None: 
     cols = df.columns 

    df1 = df.copy()[cols] 

    while True: 
     mon_inc = (df1.diff().fillna(0) >= 0).all(axis=1) 
     if mon_inc.all(): 
      break 
     df1 = df1[mon_inc] 
    return df1 
+1

素早くお返事ありがとうございます。解決策は良く見えます。ループの回数は私の用途にはあまり大きくない。 – steller

+0

'cummax'を使って更新された解決策を確認してください –

+1

うわー!驚くべき;-) (自分自身:RTFM ...)スコアの不足のため残念ながら私はあなたに投票できませんが、後で復帰します;-) – steller

関連する問題