3

しきい値に基づいてシリーズからデータを選択しています。

>>> s = pd.Series(np.random.randn(5))
>>> s
0   -0.308855
1   -0.031073
2    0.872700
3   -0.547615
4    0.633501
dtype: float64
>>> cfg = {'threshold' : 0 , 'op' : 'less' }
>>> ops = {'less' : '<', 'more': '>' , 'equal': '==' , 'not equal' : '!='}
>>> ops[cfg['op']]
'<'
>>> s[s < cfg['threshold']]
0   -0.308855
1   -0.031073
3   -0.547615
dtype: float64

「<」の代わりに、コードの最後の行で ops[cfg['op']] を使用したい。必要に応じて ops dict の key 、値を変更します (< の代わりに -lt のように)。これはどのように行うことができますか?

4

2 に答える 2

2

オペレーターの代わりになるメソッドの辞書を定義します。

import operator    
d = {
         'more'  : operator.gt,
         'less'  : operator.lt,
         'equal' : operator.eq, 
         'not equal' : operator.ne
   }

次に、辞書にインデックスを付けて、関数パラメーターを適用します。

m = d[cfg['op']](s, cfg['threshold'])
m

0    False
1     True
2     True
3    False
4    False
dtype: bool

s[m]

1   -0.262054
2   -1.300810
dtype: float64

ここ、

d[cfg['op']](s, cfg['threshold']) 

に翻訳されます

operator.lt(s, 0)
于 2017-09-26T08:40:11.230 に答える