我有以下数据框,名为 Utilidad
Argentina Bolivia Chile España Uruguay 2004 3 6 1 3 2 2005 5 1 4 1 5
我使用
计算2004年和2005年之间的差异Utilidad.ix['resta']=Utilidad.ix[2005]-Utilidad.ix[2004]
现在我正在尝试创建两个额外的行,一个是积极的结果差异,另一个是负面的,这样的事情
Argentina Bolivia Chile España Uruguay 2004 3 6 1 3 2 2005 5 1 4 1 5 resta 2 -5 3 -2 3 positive 2 0 3 0 3 negative 0 -5 0 -2 0
我唯一能做的就是有一个额外的栏目告诉我“resta”是否为正,使用
Utilidad.ix['boleano'][Utilidad.ix['resta']>0]
有人可以帮我创建另外两行吗?
由于
答案 0 :(得分:1)
您可以使用numpy.where
df.ix['positive'] = np.where(df.ix['resta'] > 0, df.ix['resta'], 0)
df.ix['negative'] = np.where(df.ix['resta'] < 0, df.ix['resta'], 0)
答案 1 :(得分:1)
numpy.clip
在这里会很方便,或者只是计算它。
In [35]:
Utilidad.ix['positive']=np.clip(Utilidad.ix['resta'], 0, np.inf)
Utilidad.ix['negative']=np.clip(Utilidad.ix['resta'], -np.inf, 0)
#or
Utilidad.ix['positive']=(Utilidad.ix['resta']+Utilidad.ix['resta'].abs())/2
Utilidad.ix['negative']=(Utilidad.ix['resta']-Utilidad.ix['resta'].abs())/2
print Utilidad
Argentina Bolivia Chile España Uruguay
id
2004 3 6 1 3 2
2005 5 1 4 1 5
resta 2 -5 3 -2 3
positive 2 0 3 0 3
negative 0 -5 0 -2 0
[5 rows x 5 columns]
一些速度比较:
%timeit (Utilidad.ix['resta']-Utilidad.ix['resta'].abs())/2
1000 loops, best of 3: 627 µs per loop
In [36]:
%timeit Utilidad.ix['positive'] = np.where(Utilidad.ix['resta'] > 0, Utilidad.ix['resta'], 0)
1000 loops, best of 3: 647 µs per loop
In [38]:
%timeit Utilidad.ix['positive']=np.clip(Utilidad.ix['resta'], 0, 100)
100 loops, best of 3: 2.6 ms per loop
In [45]:
%timeit Utilidad.ix['resta'].clip_upper(0)
1000 loops, best of 3: 1.32 ms per loop
答案 2 :(得分:1)
这里要做的观察是负数是0的最小值和行:
In [11]: np.minimum(df.loc['resta'], 0) # negative
Out[11]:
Argentina 0
Bolivia -5
Chile 0
España -2
Uruguay 0
Name: resta, dtype: int64
In [12]: np.maximum(df.loc['resta'], 0) # positive
Out[12]:
Argentina 2
Bolivia 0
Chile 3
España 0
Uruguay 3
Name: resta, dtype: int64
注意:如果您关心速度,那么转置DataFrame是有意义的,因为追加列要比追加行便宜得多。
您可以使用loc附加一行:
df.loc['negative'] = np.minimum(df.loc['resta'], 0)