Extract the Crossing Points of equator

This code should find the equatorial crossing latitudes. seems to work but not complete.

latitude = np.array([10, -5, -2, 8, -12, 15, 0, -3, 7, -9])

equatorial_crossing_indices = np.where(np.sign(latitude[:-1]) != np.sign(latitude[1:]))[0] + 1

plt.axhline(0, color=‘black’, linestyle=‘–’, label=‘Equator’)
plt.title('Latitude Data with Equatorial Crossings ')

Any comments? This is example satellite latitude and i want to get where it crosses equator.

I dont have much to contribute but maybe the linestyle should be intermittent line linestyle=‘–-’

What does “seems to work but not complete” mean? Is there a problem?

The code is not correctly giving the crossing points. it counts 0 as crossing point.

In the example you have, that would be correct. It’s crossing from 15 to -3, and you get a measurement when it’s right at 0. But in other cases you might consider it wrong: if you want right up to the equator but then back without crossing.

You’ll have to look into how np.sign works around zero and deal with the edge cases.

1 Like

Hi !

I faced the exact same problem on one of my projects some time ago. and was able to find answers in this thread: python - How to detect a sign change for elements in a numpy array - Stack Overflow.
Hope this helps !

Thank you Antoine!

I was looking at that explanation before posting my question here. I am not getting the correct code when the list has 0 as its elements. 0 shouldn’t be counted as one of the crossing points, right? So can you kindly share the correct and final code you used to detect that? Crossing is when there is sign change (either - to + or + to - but no crossing at 0)
Thank you!

I found the explanations on StackOverflow quite clear, including for handling zeros !
Anyway, here’s something similar to what I came up with, adapted to your specific context:

import numpy as np
from matplotlib import pyplot as plt

latitude = np.array([0, 0, -10, 0, 5, -2, 8, 0, -12, -14, 15, 0, 0, -3, 7, 10, -9, 0, 0])
sig = np.sign(latitude)

# Case when there are only zeros
if not sig.any():
    raise ValueError

# Eliminate last zeros if array ends with zeros
# They take the same sign as the last non-zero value
if sig[-1] == 0:
  max_non_zero_index = np.max(np.where(sig != 0)[0])
  sig[max_non_zero_index:] = sig[max_non_zero_index]

# Eliminate other zeros
# They take the same sign as the next non-zero value
while (zeros := sig == 0).any():
    sig[zeros] = np.roll(sig, -1)[zeros]

equatorial_crossing_indices = np.nonzero(np.diff(sig))

            latitude[equatorial_crossing_indices], color='red')
plt.axhline(0, color='black', linestyle='--', alpha=0.3, label='Equator')
plt.title('Latitude Data with Equatorial Crossings ')

It handles zeros at the beginning and end, as well as consecutive zeros. Only runs on Python 3.8+ because I use the walrus operator.

1 Like

This works! Huge Thank you Antoine!