Neil
Neil

Reputation: 8247

subtracting a number from pandas series except specific element

I have a pandas series like this.

cluster_grtr_6
Out[100]: 
Clusters
Cluster 1    7
Cluster 4    7
Cluster 5    8
Name: quant_bought, dtype: int64

And after applying some condition I get a variable a.

a
Out[101]: 
3    Cluster 5
Name: Clusters, dtype: object

I want to subtract 6 from every element of the series except the one which is in a

So, the final output should look like this

Clusters
Cluster 1    1
Cluster 4    1
Cluster 5    8

for subtraction every element I can simply do

(cluster_grtr_6 - 6)

Upvotes: 0

Views: 75

Answers (2)

Anton Protopopov
Anton Protopopov

Reputation: 31692

Alternatively you could use following (if you have only one value in a):

s = pd.Series([7,7,8], index=['Cluster 1', 'Cluster 4', 'Cluster 5'])
a = pd.Series(['Cluster 5'], index = [3])

In [42]: 6*(s.index != a.iloc[0])
Out[42]: array([6, 6, 0])

In [43]: s - 6*(s.index != a.iloc[0])
Out[43]:
Cluster 1    1
Cluster 4    1
Cluster 5    8
dtype: int64

In [44]: %timeit s - 6 * ~s.index.isin(a)
10000 loops, best of 3: 166 us per loop

In [45]: %timeit s - 6*(s.index != a.iloc[0])
10000 loops, best of 3: 144 us per loop

It's a little bit faster but could be used only with one variable in a

Upvotes: 1

TomAugspurger
TomAugspurger

Reputation: 28956

You can use a boolean mask. First find the index labels in a

In [64]: s.index.isin(a)
Out[64]: array([False, False,  True], dtype=bool)

Then use the fact that True is treated as 1 and False as 0 in numeric operations

In [65]: result = s - 6 * ~s.index.isin(a)

In [66]: result
Out[66]:
cluster 1    1
cluster 4    1
cluster 5    8
dtype: int64

Upvotes: 2

Related Questions