Him
Him

Reputation: 5549

Pandas subtract series by iloc, not by index

I have two pd.Series:

>>> a = pd.Series([1,2,3],index=[1,2,3])
>>> b = pd.Series([2,3,4],index=[2,3,4])

I would like to subtract these two series according to the elements' .iloc, not the index, and then get back the index of the first (or second, I don't care, really) Series.

Desired output:

>>> a - b
1    -1
2    -1
3    -1
dtype: float64

What actually comes out is:

>>> a - b
1    NaN
2    0.0
3    0.0
4    NaN
dtype: float64

Upvotes: 3

Views: 519

Answers (2)

piRSquared
piRSquared

Reputation: 294508

@DSM's comment is what I recommend.
However, I'll show how you can do this in place for pandas.Series

a.values[:] -= b.values
a

1   -1
2   -1
3   -1
dtype: int64

You can also do the the same thing with:

a.loc[:] -= b.values

Or

a.iloc[:] -= b.values

Using loc or iloc are more idiomatic Pandas.

Upvotes: 3

jpp
jpp

Reputation: 164783

You can do this via accessing numpy array representation:

res = pd.Series(a.values - b.values, index=a.index)

print(res)

# 1   -1
# 2   -1
# 3   -1
# dtype: int64

Upvotes: 4

Related Questions