2015-12-30 6 views
5

のパンダのget_dummiesからオープン境界指標を作成し、我々はqcut境界からオープン境界を作成します([U '[5、30]'、U '(30、70]']、DTYPEは= 'オブジェクト')我々はbopensを作る:qcutと<em>歳の</em>として数値<em>年齢</em>パンダ列、離散化から離散化数値

>>> bopens = get_open_bounds(df) 
>>> bopens 
# ['(-inf, 5]', '(-inf, 30]', '(-inf, 70]', '(5, +inf)', '(30, +inf)', '(70, +inf)'] 

その後、我々は、ダミー/インジケータにカテゴリ変数を変換しますget_dummiesを持つ変数:私はオープン境界列を持つデータフレームを豊かにしたい

df = pd.get_dummies(df) 
print df 
# age ageD_[5, 30] ageD_(30, 70] 
# 0 5    1    0 
# 1 23    1    0 
# 2 43    0    1 
# 3 70    0    1 
# 4 30    1    0 

、df.shapeは かなり大きい、〜(10E6、32)になります。各ラインに6本のボトルを作る最善の方法は何ですか?

>>> df 
    age age_[5, 30] age_(30, 70] (-inf, 5] (-inf, 30] (-inf, 70] (5, +inf) (30, +inf) (70, +inf) 
0 5   1    0   1   1   1   0   0   0 
1 23   1    0   0   1   1   1   0   0 
2 43   0    1   0   0   1   1   1   0 
3 70   0    1   0   0   1   1   1   0 
4 30   1    0   0   1   1   1   0   0 

がPS:bopensを作るために使用get_open_bounds

ターゲットDFはこの1つのようになります。

def get_open_bounds(df): 
    bounds = [(int(x[1:]), int(y[:-1])) for x, y in 
      [c.split(', ') for c in df.ageD.cat.categories]] 
    bounds = list(chain(*bounds)) 
    bounds 
    # [5, 30, 30, 70] 

    # to get uniques, keeping the order 
    bounds = [b for idx, b in enumerate(bounds) if b not in bounds[:idx]] 

    # make the open bounds 
    bopens = ["(-inf, {}]".format(b) for b in bounds] + \ 
      ["({}, +inf)".format(b) for b in bounds] 
    return bopens 

答えて

2

IIUC、あなたは、放送のビットでこれを行うことができます。

df['ageD'], bins = pd.qcut(df.iloc[:, 0], 2, retbins=True) 
left = (df["age"].values <= bins[:,None]).T.astype(int) 
dl = pd.DataFrame(left, columns=["(-inf, {}]".format(b) for b in bins]) 
dr = pd.DataFrame(1-left, columns=["({}, +inf)".format(b) for b in bins]) 
dout = pd.concat([pd.get_dummies(df), dl, dr], axis=1) 

が私に

123を与える
>>> dout 
    age ageD_[5, 30] ageD_(30, 70] (-inf, 5] (-inf, 30] (-inf, 70] (5, +inf) (30, +inf) (70, +inf) 
0 5    1    0   1   1   1   0   0   0 
1 23    1    0   0   1   1   1   0   0 
2 43    0    1   0   0   1   1   1   0 
3 70    0    1   0   0   1   1   1   0 
4 30    1    0   0   1   1   1   0   0 

注1:retbins = Trueを追加することで、自分自身でビンを取得して、厄介な文字列の解析を避けることができます。注:#2:暗黙の "right = 1 - left"を実行すると、年齢はNaNでないと仮定しているので、> =または<のいずれかが真でなければなりません。 )

Note#3:実際には、フレームのコンストラクタdf.indexも渡す必要があります。例に正準インデックスがありますが、それはあなたの中では当てはまらないかもしれません。実データ。

+0

df.indexをフレームコンストラクタに渡すとはどういう意味ですか? – user3313834

+0

@ user3313834:DataFrameには、 'data'(何がいっぱいになるか)、' columns'(列の名前)、 'index'など、いくつかの引数があります。私は 'index'を渡さなかったので、' dl'と 'dr'はインデックス0,1,2,3を取得します。' df'に0,1,2,3 ..などがなければ、インデックスが一致しないため、連結によって予期しない結果が発生します。 – DSM

関連する問題