0

pandas データフレーム df に以下が含まれている場合:

    A    B    C    D
a   1    2    3    4
b   2    NaN  NaN  5
c   NaN  7    NaN  2
d   NaN  2    4    3

結果のデータフレームを取得するために、最初の行を残りのすべての行に、数値が含まれている場所にのみ追加するにはどうすればよいですか?

    A    B    C    D
b   3    NaN  NaN  9
c   NaN  9    NaN  6
d   NaN  4    7    7

これを実行してから、行名の辞書を作成し、最初のテーブルの各行の列の積を 2 番目のテーブルの同じ行で割り、値を辞書に保存します。私はこれを実行する作業コードを持っています (以下) が、「PANDAS」では不十分であり、実行したい単純なタスクに対して複雑すぎるのではないかと心配しています。最適な解決策がありますか、それとも明らかな何かが欠けていますか?

Pandas コードがまだ行を反復処理する必要がある場合、それは価値がありませんが、これをインプレースで行う方法があるべきだと思います。

コード:

import numpy as np
import pandas as pd

dindex = [1,2,3] #indices of drugs to select (set this)

def get_drugs(): #generates random "drug characteristics" as pandas df
    cduct = ['dose','g1','g2','g3','g4','g5']
    drg = ['d1','d2','d3','d4']
    return pd.DataFrame(abs(np.random.randn(6,4)),index=cduct,columns=drg)

def sel_drugs(dframe, selct): #removes unwanted drugs from df.
    #Pass df and dindex to this function
    return dframe.iloc[:,selct].values, dframe[1:].index.tolist()
    #returns a tuple of [values, names]

def cal_conduct(val, cnames): #calculates conductance scaling.
    #Pass values and names to this function
    cduct = {} #initialize dict
    for ix, gname in enumerate(cnames):
        _top = val[ix+1]; _bot = val[0]+val[ix+1]
        cduct[gname] = (np.product(_top[np.isfinite(_top)])/
                        np.product(_bot[np.isfinite(_bot)]))
    return cduct #return a dictionary of scaling factors

def main():
    selection =  sel_drugs(get_drugs(),dindex)
    print cal_conduct(selection[0], selection[1])

main()
4

2 に答える 2

3

パンダは自動的に整列/ブロードキャストするので、これは簡単です

In [8]: df
Out[8]: 
    A   B   C  D
a   1   2   3  4
b   2 NaN NaN  5
c NaN   7 NaN  2
d NaN   2   4  3

In [11]: df.iloc[1:] + df.iloc[0]
Out[11]: 
    A   B   C  D
b   3 NaN NaN  9
c NaN   9 NaN  6
d NaN   4   7  7

2番目の部分は、正しく読んでいればこれです

In [12]: df2 = df.iloc[1:] + df.iloc[0]

In [13]: df.prod()
Out[13]: 
A      2
B     28
C     12
D    120
dtype: float64

In [14]: df2/df.prod()
Out[14]: 
     A         B         C         D
b  1.5       NaN       NaN  0.075000
c  NaN  0.321429       NaN  0.050000
d  NaN  0.142857  0.583333  0.058333
于 2013-10-12T21:24:14.870 に答える
0

@Jeffの回答に基づくコードを次に示します。少なくともテスト データが小さい場合は、約 40% 遅くなりますが、より単純です。

import numpy as np
import pandas as pd

dindex = [1,2,3] #indices of drugs to select (set this)

def get_drugs(): #generates random "drug characteristics" as pandas df
    cduct = ['dose','g1','g2','g3','g4','g5']
    drg = ['d1','d2','d3','d4']
    return pd.DataFrame(abs(np.random.randn(6,4)),index=cduct,columns=drg)

def cal_conduct(frame,selct): #calculates conductance scaling.
    #Pass df with selections made
    s = frame.iloc[:,selct]
    cduct = s.iloc[1:].prod(1)/(s.iloc[0]+s.iloc[1:]).prod(1)
    return cduct.to_dict() #return a dictionary of scaling factors

def main():
    scaling = cal_conduct(get_drugs(), dindex)
    print scaling

main()
于 2013-10-13T16:38:33.960 に答える