Convert sine wave signal to square wave signal
What you can do is process this signal with a windowed RMS function (I'm writing in matlab code, but it can easily be translated in python) :
windowlength = 5; %you can change that, but keep it odd
hw = (windowlength-1)/2; %hw stands for &quot;half window&quot;
%pre-assigning the output RMS signal
sig_RMS = zeros(1,length(sig)); 
%I'm adding zeros the the signal's left and right for boundary calculation
sig_zero_padded = [zeros(hw,1), sig, zeros(hw,1)];

sig_zero_padded = sig_zero_padded.^2; %squaring the samples
for i=(hw+1):(length(sig_zero_padded)-hw)
   % calculating square-mean inside the window and assigning the result
   %to the appropriate sample in sig_RMS
  sig_RMS(i-hw) = sqrt(mean(sig_zero_padded(i-hw:i+hw)));
end

Then you set a minimum value for which superior values of the RMS signal will be assigned to 1, and the other to zero :
trigger = 0.5; %I chose arbitrarily
square_sig = (sig_RMS &gt; trigger);

And you should get your square signal.
What we are doing here, in simple language, is taking little bits of the signal and calculating the RMS value of each bit. If this calculated value is significant enough to be considered as &quot;not noise&quot;, we assign '1' to it.
EDIT :
I managed to compute it and it worked. Note that I had to take Fs = 10^5 because my computer does not have enough capacity for Fs = 10^6.
Here is the signal (blue), and the calculated RMS signal (red) for windowlength = 8191 :

Then I set trigger = 0.4 and obtained two crystal clear zones identifying the useful signal :

So in conclusion :

Set windowlength to get the RMS signal mean value far enough of the noise while keeping accuracy. In my case it was approximately 1 % of the total number of samples.
Set trigger between the RMS crests and the noise

However, I'm having that feeling that I'm reinventing something so feel free to look up for some literature about this method, I'm sure someone did the math to obtain optimal values of windowslength and trigger. ;)