2016-04-06 1 views
2

私は次のようになり、次のdf行パンダ上の共有機能を適用DF

Array = np.array([[87, 70, 95], 
    [52, 47, 44], 
    [44, 97, 94], 
    [79, 36, 2]]) 

df_test = pd.DataFrame(Array, columns=['Apple', 'Banana', 'Tomato'],index=[['Joe', 'Steve', 'Wes', 'Jim']]) 

あります

 Apple Banana Tomato 
Joe  87  70  95 
Steve  52  47  44 
Wes  44  97  94 
Jim  79  36  2 

を、私はラインで各経費のシェアを計算したいが、私は見つけることはありません。それはのようになります。

df_test.apply(lambda: x/max(line),axis=2) 

と結果は次のようになります。

 Apple Banana Tomato 
Joe 0.35 0.27 0.37 
.  .  .  . 

しかし、私はラムダ関数内の各ラインの最大を計算する方法を見つけることができません。誰かが考えを持っていますか? ありがとうございます!

答えて

2

あなたは、行単位sumによりdivしたい:

In [111]: 
df_test.div(df_test.sum(axis=1), axis=0) * 100 

Out[111]: 
      Apple Banana Tomato 
Joe 0.345238 0.277778 0.376984 
Steve 0.363636 0.328671 0.307692 
Wes 0.187234 0.412766 0.400000 
Jim 0.675214 0.307692 0.017094 

あなたが精度を設定したい場合は、roundを呼び出すことができます。

In [112]: 
df_test.div(df_test.sum(axis=1), axis=0).round(2) 

Out[112]: 
     Apple Banana Tomato 
Joe  0.35 0.28 0.38 
Steve 0.36 0.33 0.31 
Wes  0.19 0.41 0.40 
Jim  0.68 0.31 0.02 
+0

あなたはdivの機能が正確に何をすべきかを説明してもらえますか?私が分かっていれば分割されているだけではありません。 –

+1

これは、Dfを和の結果に対して除算しています。何が起きているのかは、インデックスと列を揃えていることです。これがどのように動作するかを見るために私の他の答えを見ることができます:http://stackoverflow.com/questions/29954263/what-放送中のパンデミックの文書化/ 29955358#29955358 – EdChum