Einar
Einar

Reputation: 4933

pandas: Change one Series by using a second one with the same index

Recently I'm doing some work with two Series in pandas:

Example data:

first_series = pandas.Series([0.000003, 0.004991, 0.004991])
second_series = pandas.Series(["Plus", "Minus", np.nan], dtype="object",
                              index=first_series.index)

(in the real-world scenario, the second Series is built programmatically using the same index as the first one, but here it's just a simplified example)

I'm doing first some manipulation:

first_series = np.log2(1 / first_series)

Then I'd need to invert the sign (multiply by -1) of the corresponding "Minus" entries, and turn to NaN the ones that in the second series are NaN.

The latter part works OK:

first_series[np.invert(second_series.notnull())] = np.nan

print first_series

0    18.567557
1     7.646459
2          NaN
Name: Example data

However I'm kind of stuck with the former part. How can I use the information in the second Series (given that they are identically-indexed) to switch the sign in the first Series?

As a reference, after the application, first_series should become like this:

0    18.567557
1    -7.646459
2          NaN
Name: Example data

Upvotes: 1

Views: 457

Answers (1)

eumiro
eumiro

Reputation: 213125

first_series[second_series == 'Minus'] *= -1
first_series[second_series.isnull()] = np.nan

gives you:

0    18.346606
1    -7.646455
2          NaN

Upvotes: 2

Related Questions