あなたは、新しいSeries
を作成し、それらを比較し、新しい列のnumpy.where
を使用することができます。
a = (df['throughtput'] - 2)/2
b = (df['throughtput'] - 7)/7
df['pct'] = np.where(a < b, a, b)
print (df)
x throughtput pct
0 1 3 -0.571429
1 4 4 -0.428571
2 7 9 0.285714
ソリューションconcat
とし、DataFrame.min
:
a = (df['throughtput'] - 2)/2
b = (df['throughtput'] - 7)/7
df['pct'] = pd.concat([a,b], axis=1).min(axis=1)
print (df)
x throughtput pct
0 1 3 -0.571429
1 4 4 -0.428571
2 7 9 0.285714
それともnumpy.column_stack
で2次元配列を作成し、分を得るにはnumpy.amin
:
a = (df['throughtput'] - 2)/2
b = (df['throughtput'] - 7)/7
df['pct'] = np.amin(np.column_stack([a,b]), axis=1)
print (df)
x throughtput pct
0 1 3 -0.571429
1 4 4 -0.428571
2 7 9 0.285714
a = (df['throughtput'].values - 2)/2
b = (df['throughtput'].values - 7)/7
df['pct'] = np.amin(np.column_stack([a,b]), axis=1)
print (df)
x throughtput pct
0 1 3 -0.571429
1 4 4 -0.428571
2 7 9 0.285714
タイミング:
N = 1000000
#N = 10
df = pd.DataFrame({'x': np.random.randint(10,size=N),
'throughtput':np.random.randint(10,size=N)})
print (df)
In [50]: %%timeit
...: a = (df['throughtput'] - 2)/2
...: b = (df['throughtput'] - 7)/7
...: df['pct'] = np.where(a < b, a, b)
...:
10 loops, best of 3: 21.1 ms per loop
In [51]: %%timeit
...: a = (df['throughtput'] - 2)/2
...: b = (df['throughtput'] - 7)/7
...: df['pct'] = pd.concat([a,b], axis=1).min(axis=1)
...:
10 loops, best of 3: 56.4 ms per loop
In [52]: %%timeit
...: a = (df['throughtput'] - 2)/2
...: b = (df['throughtput'] - 7)/7
...: df['pct'] = np.amin(np.column_stack([a,b]), axis=1)
...:
10 loops, best of 3: 35.1 ms per loop
In [53]: %%timeit
...: a = (df['throughtput'].values - 2)/2
...: b = (df['throughtput'].values - 7)/7
...: df['pct'] = np.amin(np.column_stack([a,b]), axis=1)
...:
10 loops, best of 3: 38.5 ms per loop
もう一つの答えTiny.Dによって:
In [54]: %%timeit
...: df['cal_1'] = (df.throughtput - 2)/2
...: df['cal_2'] = (df.throughtput - 7)/7
...: df['pct'] = df[['cal_1','cal_2']].min(axis=1)
...: df[['x','throughtput','pct']]
...:
10 loops, best of 3: 73.7 ms per loop
In [55]: %%timeit
...: df['pct']=[min(i,j) for i,j in (zip((df.throughtput - 2)/2,(df.throughtput - 7)/7))]
...:
1 loop, best of 3: 435 ms per loop