π‘ Top 50 Operations for Audio Processing in Python
Note: Most examples use
I. Basic Loading, Saving & Properties
β’ Load an audio file (any format).
β’ Export (save) an audio file.
β’ Get duration in milliseconds.
β’ Get frame rate (sample rate).
β’ Get number of channels (1 for mono, 2 for stereo).
β’ Get sample width in bytes (e.g., 2 for 16-bit).
II. Playback & Recording
β’ Play an audio segment.
β’ Record audio from a microphone for 5 seconds.
III. Slicing & Concatenating
β’ Get a slice (e.g., the first 5 seconds).
β’ Get a slice from the end (e.g., the last 3 seconds).
β’ Concatenate (append) two audio files.
β’ Repeat an audio segment.
β’ Crossfade two audio segments.
IV. Volume & Effects
β’ Increase volume by 6 dB.
β’ Decrease volume by 3 dB.
β’ Fade in from silence.
β’ Fade out to silence.
β’ Reverse the audio.
β’ Normalize audio to a maximum amplitude.
β’ Overlay (mix) two tracks.
V. Channel Manipulation
β’ Split stereo into two mono channels.
β’ Create a stereo segment from two mono segments.
β’ Convert stereo to mono.
VI. Silence & Splitting
β’ Generate a silent segment.
β’ Split audio based on silence.
VII. Working with Raw Data (NumPy & SciPy)
Note: Most examples use
pydub. You need ffmpeg installed for opening/exporting non-WAV files. Install libraries with pip install pydub librosa sounddevice scipy numpy.I. Basic Loading, Saving & Properties
β’ Load an audio file (any format).
from pydub import AudioSegment
audio = AudioSegment.from_file("sound.mp3")
β’ Export (save) an audio file.
audio.export("new_sound.wav", format="wav")β’ Get duration in milliseconds.
duration_ms = len(audio)
β’ Get frame rate (sample rate).
rate = audio.frame_rate
β’ Get number of channels (1 for mono, 2 for stereo).
channels = audio.channels
β’ Get sample width in bytes (e.g., 2 for 16-bit).
width = audio.sample_width
II. Playback & Recording
β’ Play an audio segment.
from pydub.playback import play
play(audio)
β’ Record audio from a microphone for 5 seconds.
import sounddevice as sd
from scipy.io.wavfile import write
fs = 44100 # Sample rate
seconds = 5
recording = sd.rec(int(seconds * fs), samplerate=fs, channels=2)
sd.wait() # Wait until recording is finished
write('output.wav', fs, recording)
III. Slicing & Concatenating
β’ Get a slice (e.g., the first 5 seconds).
first_five_seconds = audio[:5000] # Time is in milliseconds
β’ Get a slice from the end (e.g., the last 3 seconds).
last_three_seconds = audio[-3000:]
β’ Concatenate (append) two audio files.
combined = audio1 + audio2
β’ Repeat an audio segment.
repeated = audio * 3
β’ Crossfade two audio segments.
# Fades out audio1 while fading in audio2
faded = audio1.append(audio2, crossfade=1000)
IV. Volume & Effects
β’ Increase volume by 6 dB.
louder_audio = audio + 6
β’ Decrease volume by 3 dB.
quieter_audio = audio - 3
β’ Fade in from silence.
faded_in = audio.fade_in(2000) # 2-second fade-in
β’ Fade out to silence.
faded_out = audio.fade_out(3000) # 3-second fade-out
β’ Reverse the audio.
reversed_audio = audio.reverse()
β’ Normalize audio to a maximum amplitude.
from pydub.effects import normalize
normalized_audio = normalize(audio)
β’ Overlay (mix) two tracks.
# Starts playing 'overlay_sound' 5 seconds into 'main_sound'
mixed = main_sound.overlay(overlay_sound, position=5000)
V. Channel Manipulation
β’ Split stereo into two mono channels.
left_channel, right_channel = audio.split_to_mono()
β’ Create a stereo segment from two mono segments.
stereo_sound = AudioSegment.from_mono_segments(left_channel, right_channel)
β’ Convert stereo to mono.
mono_audio = audio.set_channels(1)
VI. Silence & Splitting
β’ Generate a silent segment.
one_second_silence = AudioSegment.silent(duration=1000)
β’ Split audio based on silence.
from pydub.silence import split_on_silence
chunks = split_on_silence(
audio,
min_silence_len=500,
silence_thresh=-40
)
VII. Working with Raw Data (NumPy & SciPy)
β’ Get raw audio data as a NumPy array.
β’ Create a Pydub segment from a NumPy array.
β’ Read a WAV file directly into a NumPy array.
β’ Write a NumPy array to a WAV file.
β’ Generate a sine wave.
VIII. Audio Analysis with Librosa
β’ Load audio with Librosa.
β’ Estimate tempo (Beats Per Minute).
β’ Get beat event times in seconds.
β’ Decompose into harmonic and percussive components.
β’ Compute a spectrogram.
β’ Compute Mel-Frequency Cepstral Coefficients (MFCCs).
β’ Compute Chroma features (related to musical pitch).
β’ Detect onset events (the start of notes).
β’ Pitch shifting.
β’ Time stretching (change speed without changing pitch).
IX. More Utilities
β’ Detect leading silence.
β’ Get the root mean square (RMS) energy.
β’ Get the maximum possible RMS for the audio format.
β’ Find the loudest section of an audio file.
β’ Change the frame rate (resample).
β’ Create a simple band-pass filter.
β’ Convert file format in one line.
β’ Get the raw bytes of the audio data.
β’ Get the maximum amplitude.
β’ Match the volume of two segments.
#Python #AudioProcessing #Pydub #Librosa #SignalProcessing
βββββββββββββββ
By: @DataScienceM β¨
import numpy as np
samples = np.array(audio.get_array_of_samples())
β’ Create a Pydub segment from a NumPy array.
new_audio = AudioSegment(
samples.tobytes(),
frame_rate=audio.frame_rate,
sample_width=audio.sample_width,
channels=audio.channels
)
β’ Read a WAV file directly into a NumPy array.
from scipy.io.wavfile import read
rate, data = read("sound.wav")
β’ Write a NumPy array to a WAV file.
from scipy.io.wavfile import write
write("new_sound.wav", rate, data)
β’ Generate a sine wave.
import numpy as np
sample_rate = 44100
frequency = 440 # A4 note
duration = 5
t = np.linspace(0., duration, int(sample_rate * duration))
amplitude = np.iinfo(np.int16).max * 0.5
data = amplitude * np.sin(2. * np.pi * frequency * t)
# This array can now be written to a file
VIII. Audio Analysis with Librosa
β’ Load audio with Librosa.
import librosa
y, sr = librosa.load("sound.mp3")
β’ Estimate tempo (Beats Per Minute).
tempo, beat_frames = librosa.beat.beat_track(y=y, sr=sr)
β’ Get beat event times in seconds.
beat_times = librosa.frames_to_time(beat_frames, sr=sr)
β’ Decompose into harmonic and percussive components.
y_harmonic, y_percussive = librosa.effects.hpss(y)
β’ Compute a spectrogram.
import numpy as np
D = librosa.stft(y)
S_db = librosa.amplitude_to_db(np.abs(D), ref=np.max)
β’ Compute Mel-Frequency Cepstral Coefficients (MFCCs).
mfccs = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=13)
β’ Compute Chroma features (related to musical pitch).
chroma = librosa.feature.chroma_stft(y=y, sr=sr)
β’ Detect onset events (the start of notes).
onset_frames = librosa.onset.onset_detect(y=y, sr=sr)
onset_times = librosa.frames_to_time(onset_frames, sr=sr)
β’ Pitch shifting.
y_pitched = librosa.effects.pitch_shift(y, sr=sr, n_steps=4) # Shift up 4 semitones
β’ Time stretching (change speed without changing pitch).
y_fast = librosa.effects.time_stretch(y, rate=2.0) # Double speed
IX. More Utilities
β’ Detect leading silence.
from pydub.silence import detect_leading_silence
trim_ms = detect_leading_silence(audio)
trimmed_audio = audio[trim_ms:]
β’ Get the root mean square (RMS) energy.
rms = audio.rms
β’ Get the maximum possible RMS for the audio format.
max_possible_rms = audio.max_possible_amplitude
β’ Find the loudest section of an audio file.
from pydub.scipy_effects import normalize
loudest_part = normalize(audio.strip_silence(silence_len=1000, silence_thresh=-32))
β’ Change the frame rate (resample).
resampled = audio.set_frame_rate(16000)
β’ Create a simple band-pass filter.
from pydub.scipy_effects import band_pass_filter
filtered = band_pass_filter(audio, 400, 2000) # Pass between 400Hz and 2000Hz
β’ Convert file format in one line.
AudioSegment.from_file("music.ogg").export("music.mp3", format="mp3")β’ Get the raw bytes of the audio data.
raw_data = audio.raw_data
β’ Get the maximum amplitude.
max_amp = audio.max
β’ Match the volume of two segments.
matched_audio2 = audio2.apply_gain(audio1.dBFS - audio2.dBFS)
#Python #AudioProcessing #Pydub #Librosa #SignalProcessing
βββββββββββββββ
By: @DataScienceM β¨
β€3
π€π§ HunyuanWorld-Mirror: Tencentβs Breakthrough in Universal 3D Reconstruction
ποΈ 03 Nov 2025
π AI News & Trends
The race toward achieving universal 3D understanding has reached a significant milestone with Tencentβs HunyuanWorld-Mirror, a cutting-edge open-source model designed to revolutionize 3D reconstruction. In an era dominated by visual intelligence and immersive digital experiences, this new model stands out by offering a feed-forward, geometry-aware framework that can predict multiple 3D outputs in a single ...
#HunyuanWorld #Tencent #3DReconstruction #UniversalAI #GeometryAware #OpenSourceAI
ποΈ 03 Nov 2025
π AI News & Trends
The race toward achieving universal 3D understanding has reached a significant milestone with Tencentβs HunyuanWorld-Mirror, a cutting-edge open-source model designed to revolutionize 3D reconstruction. In an era dominated by visual intelligence and immersive digital experiences, this new model stands out by offering a feed-forward, geometry-aware framework that can predict multiple 3D outputs in a single ...
#HunyuanWorld #Tencent #3DReconstruction #UniversalAI #GeometryAware #OpenSourceAI
π‘ Top 50 Operations for Signal Processing in Python
Note: Most examples use
I. Signal Generation
β’ Create a time vector.
β’ Generate a sine wave.
β’ Generate a square wave.
β’ Generate a sawtooth wave.
β’ Generate Gaussian white noise.
β’ Generate a frequency-swept cosine (chirp).
β’ Generate an impulse signal (unit impulse).
β’ Generate a Gaussian pulse.
II. Signal Visualization & Properties
β’ Plot a signal.
β’ Calculate the mean value.
β’ Calculate the Root Mean Square (RMS).
β’ Calculate the standard deviation.
β’ Find the maximum value and its index.
III. Frequency Domain Analysis (FFT)
β’ Compute the Fast Fourier Transform (FFT).
β’ Get the frequency bins for the FFT.
β’ Plot the magnitude spectrum.
β’ Compute the Inverse FFT (IFFT).
β’ Compute the Power Spectral Density (PSD) using Welch's method.
IV. Digital Filtering
β’ Design a Butterworth low-pass filter.
β’ Apply a filter to a signal (zero-phase filtering).
β’ Design a Chebyshev Type I high-pass filter.
β’ Design a Bessel band-pass filter.
β’ Design an FIR filter using a window method.
β’ Plot the frequency response of a filter.
β’ Apply a median filter (good for salt-and-pepper noise).
β’ Apply a Wiener filter for noise reduction.
V. Resampling & Windowing
β’ Resample a signal to a new length.
β’ Decimate a signal (downsample by a factor).
β’ Create a Hamming window.
β’ Apply a window to a signal segment.
Note: Most examples use
numpy, scipy.signal, and matplotlib.pyplot. Assume they are imported as:import numpy as npfrom scipy import signalimport matplotlib.pyplot as pltI. Signal Generation
β’ Create a time vector.
fs = 1000 # Sampling frequency
t = np.linspace(0, 1, fs, endpoint=False)
β’ Generate a sine wave.
freq = 50 # Hz
sine_wave = np.sin(2 * np.pi * freq * t)
β’ Generate a square wave.
square_wave = signal.square(2 * np.pi * freq * t)
β’ Generate a sawtooth wave.
sawtooth_wave = signal.sawtooth(2 * np.pi * freq * t)
β’ Generate Gaussian white noise.
noise = np.random.normal(0, 1, len(t))
β’ Generate a frequency-swept cosine (chirp).
chirp_signal = signal.chirp(t, f0=1, f1=100, t1=1, method='linear')
β’ Generate an impulse signal (unit impulse).
impulse = signal.unit_impulse(100, 'mid') # at index 50 of 100
β’ Generate a Gaussian pulse.
gaus_pulse = signal.gausspulse(t, fc=5, bw=0.5)
II. Signal Visualization & Properties
β’ Plot a signal.
plt.plot(t, sine_wave)
plt.xlabel("Time [s]")
plt.ylabel("Amplitude")
plt.show()
β’ Calculate the mean value.
mean_val = np.mean(sine_wave)
β’ Calculate the Root Mean Square (RMS).
rms_val = np.sqrt(np.mean(sine_wave**2))
β’ Calculate the standard deviation.
std_dev = np.std(sine_wave)
β’ Find the maximum value and its index.
max_val = np.max(sine_wave)
max_idx = np.argmax(sine_wave)
III. Frequency Domain Analysis (FFT)
β’ Compute the Fast Fourier Transform (FFT).
from scipy.fft import fft, fftfreq
yf = fft(sine_wave)
β’ Get the frequency bins for the FFT.
N = len(sine_wave)
xf = fftfreq(N, 1 / fs)[:N//2]
β’ Plot the magnitude spectrum.
plt.plot(xf, 2.0/N * np.abs(yf[0:N//2]))
plt.grid()
plt.show()
β’ Compute the Inverse FFT (IFFT).
from scipy.fft import ifft
original_signal = ifft(yf)
β’ Compute the Power Spectral Density (PSD) using Welch's method.
f, Pxx_den = signal.welch(sine_wave, fs, nperseg=1024)
IV. Digital Filtering
β’ Design a Butterworth low-pass filter.
b, a = signal.butter(4, 100, 'low', analog=False, fs=fs)
β’ Apply a filter to a signal (zero-phase filtering).
noisy_signal = sine_wave + noise
filtered_signal = signal.filtfilt(b, a, noisy_signal)
β’ Design a Chebyshev Type I high-pass filter.
b, a = signal.cheby1(4, 5, 100, 'high', fs=fs) # 5dB ripple
β’ Design a Bessel band-pass filter.
b, a = signal.bessel(4, [50, 150], 'band', fs=fs)
β’ Design an FIR filter using a window method.
numtaps = 101
fir_coeffs = signal.firwin(numtaps, cutoff=100, fs=fs)
β’ Plot the frequency response of a filter.
w, h = signal.freqz(b, a, fs=fs)
plt.plot(w, 20 * np.log10(abs(h)))
β’ Apply a median filter (good for salt-and-pepper noise).
median_filtered = signal.medfilt(noisy_signal, kernel_size=3)
β’ Apply a Wiener filter for noise reduction.
wiener_filtered = signal.wiener(noisy_signal)
V. Resampling & Windowing
β’ Resample a signal to a new length.
resampled = signal.resample(sine_wave, num=500) # Resample to 500 points
β’ Decimate a signal (downsample by a factor).
decimated = signal.decimate(sine_wave, q=4) # Downsample by 4
β’ Create a Hamming window.
window = signal.windows.hamming(51)
β’ Apply a window to a signal segment.
segment = sine_wave[0:51]
windowed_segment = segment * window
VI. Convolution & Correlation
β’ Perform linear convolution.
sig1 = np.repeat([0., 1., 0.], 100)
sig2 = np.repeat([0., 1., 1., 0.], 100)
convolved = signal.convolve(sig1, sig2, mode='same')
β’ Compute cross-correlation.
# Useful for finding delays between signals
correlation = signal.correlate(sig1, sig2, mode='full')
β’ Compute auto-correlation.
# Useful for finding periodicities in a signal
autocorr = signal.correlate(sine_wave, sine_wave, mode='full')
VII. Time-Frequency Analysis
β’ Compute and plot a spectrogram.
f, t_spec, Sxx = signal.spectrogram(chirp_signal, fs)
plt.pcolormesh(t_spec, f, Sxx, shading='gouraud')
plt.show()
β’ Perform Continuous Wavelet Transform (CWT).
widths = np.arange(1, 31)
cwt_matrix = signal.cwt(chirp_signal, signal.ricker, widths)
β’ Perform Hilbert transform to get the analytic signal.
analytic_signal = signal.hilbert(sine_wave)
β’ Calculate instantaneous frequency.
instant_phase = np.unwrap(np.angle(analytic_signal))
instant_freq = (np.diff(instant_phase) / (2.0*np.pi) * fs)
VIII. Feature Extraction
β’ Find peaks in a signal.
peaks, _ = signal.find_peaks(sine_wave, height=0.5)
β’ Find peaks with prominence criteria.
peaks_prom, _ = signal.find_peaks(noisy_signal, prominence=1)
β’ Differentiate a signal (e.g., to find velocity from position).
derivative = np.diff(sine_wave)
β’ Integrate a signal.
from scipy.integrate import cumulative_trapezoid
integral = cumulative_trapezoid(sine_wave, t, initial=0)
β’ Detrend a signal to remove a linear trend.
trend = np.linspace(0, 1, fs)
trended_signal = sine_wave + trend
detrended = signal.detrend(trended_signal)
IX. System Analysis
β’ Define a system via a transfer function (numerator, denominator).
# Example: 2nd order low-pass filter
system = signal.TransferFunction([1], [1, 1, 1])
β’ Compute the step response of a system.
t_step, y_step = signal.step(system)
β’ Compute the impulse response of a system.
t_impulse, y_impulse = signal.impulse(system)
β’ Compute the Bode plot of a system's frequency response.
w, mag, phase = signal.bode(system)
X. Signal Generation from Data
β’ Generate a signal from a function.
t = np.linspace(0, 1, 500)
custom_signal = np.sinc(2 * np.pi * 4 * t)
β’ Convert a list of values to a signal array.
my_data = [0, 1, 2, 3, 2, 1, 0, -1, -2, -1, 0]
data_signal = np.array(my_data)
β’ Read signal data from a WAV file.
from scipy.io import wavfile
samplerate, data = wavfile.read('audio.wav')
β’ Create a pulse train signal.
pulse_train = np.zeros(fs)
pulse_train[::100] = 1 # Impulse every 100 samples
#Python #SignalProcessing #SciPy #NumPy #DSP
βββββββββββββββ
By: @DataScienceM β¨
π‘ Top 50 Matplotlib Commands in Python
Note: Examples assume the following imports:
I. Figure & Basic Plots
β’ Create a figure.
β’ Create a basic line plot.
β’ Show/display the plot.
β’ Save a figure to a file.
β’ Create a scatter plot.
β’ Create a bar chart.
β’ Create a horizontal bar chart.
β’ Create a histogram.
β’ Create a pie chart.
β’ Create a box plot.
β’ Display a 2D array or image.
β’ Clear the current figure.
II. Labels, Titles & Legends
β’ Add a title to the plot.
β’ Add a label to the x-axis.
β’ Add a label to the y-axis.
β’ Add a legend.
β’ Add a grid.
β’ Add text to the plot at specific coordinates.
β’ Add an annotation with an arrow.
III. Axes & Ticks
β’ Set the x-axis limits.
β’ Set the y-axis limits.
β’ Set the x-axis ticks and labels.
β’ Set the y-axis ticks and labels.
β’ Set a logarithmic scale on an axis.
β’ Set the aspect ratio of the plot.
IV. Plot Customization
β’ Set the color of a plot.
β’ Set the line style.
β’ Set the line width.
β’ Set the marker style for points.
β’ Set the transparency (alpha).
β’ Use a predefined style.
β’ Fill the area between two curves.
β’ Create an error bar plot.
β’ Add a horizontal line.
β’ Add a vertical line.
β’ Add a colorbar for plots like
V. Subplots (Object-Oriented Approach)
β’ Create a figure and a grid of subplots (preferred method).
Note: Examples assume the following imports:
import matplotlib.pyplot as pltimport numpy as npI. Figure & Basic Plots
β’ Create a figure.
fig = plt.figure(figsize=(8, 6))
β’ Create a basic line plot.
x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x))
β’ Show/display the plot.
plt.show()
β’ Save a figure to a file.
plt.savefig("my_plot.png", dpi=300)β’ Create a scatter plot.
plt.scatter(x, np.cos(x))
β’ Create a bar chart.
categories = ['A', 'B', 'C']
values = [3, 7, 2]
plt.bar(categories, values)
β’ Create a horizontal bar chart.
plt.barh(categories, values)
β’ Create a histogram.
data = np.random.randn(1000)
plt.hist(data, bins=30)
β’ Create a pie chart.
plt.pie(values, labels=categories, autopct='%1.1f%%')
β’ Create a box plot.
plt.boxplot([data, data*2])
β’ Display a 2D array or image.
matrix = np.random.rand(10, 10)
plt.imshow(matrix, cmap='viridis')
β’ Clear the current figure.
plt.clf()
II. Labels, Titles & Legends
β’ Add a title to the plot.
plt.title("Sine Wave")β’ Add a label to the x-axis.
plt.xlabel("Time (s)")β’ Add a label to the y-axis.
plt.ylabel("Amplitude")β’ Add a legend.
plt.plot(x, np.sin(x), label='Sine')
plt.plot(x, np.cos(x), label='Cosine')
plt.legend()
β’ Add a grid.
plt.grid(True)
β’ Add text to the plot at specific coordinates.
plt.text(2, 0.5, 'An important point')
β’ Add an annotation with an arrow.
plt.annotate('Peak', xy=(np.pi/2, 1), xytext=(3, 1.5),
arrowprops=dict(facecolor='black', shrink=0.05))III. Axes & Ticks
β’ Set the x-axis limits.
plt.xlim(0, 5)
β’ Set the y-axis limits.
plt.ylim(-1.5, 1.5)
β’ Set the x-axis ticks and labels.
plt.xticks([0, np.pi, 2*np.pi], ['0', '$\pi$', '$2\pi$'])
β’ Set the y-axis ticks and labels.
plt.yticks([-1, 0, 1])
β’ Set a logarithmic scale on an axis.
plt.yscale('log')β’ Set the aspect ratio of the plot.
plt.axis('equal') # Other options: 'tight', 'off'IV. Plot Customization
β’ Set the color of a plot.
plt.plot(x, np.sin(x), color='red')
β’ Set the line style.
plt.plot(x, np.sin(x), linestyle='--')
β’ Set the line width.
plt.plot(x, np.sin(x), linewidth=3)
β’ Set the marker style for points.
plt.plot(x, np.sin(x), marker='o')
β’ Set the transparency (alpha).
plt.hist(data, alpha=0.5)
β’ Use a predefined style.
plt.style.use('ggplot')β’ Fill the area between two curves.
plt.fill_between(x, np.sin(x), np.cos(x), alpha=0.2)
β’ Create an error bar plot.
y_err = 0.2 * np.ones_like(x)
plt.errorbar(x, np.sin(x), yerr=y_err)
β’ Add a horizontal line.
plt.axhline(y=0, color='k', linestyle='-')
β’ Add a vertical line.
plt.axvline(x=np.pi, color='k', linestyle='-')
β’ Add a colorbar for plots like
imshow or scatter.plt.colorbar(label='Magnitude')
V. Subplots (Object-Oriented Approach)
β’ Create a figure and a grid of subplots (preferred method).
fig, ax = plt.subplots() # Single subplot
fig, axes = plt.subplots(2, 2) # 2x2 grid of subplots
β’ Plot on a specific subplot (Axes object).
axes[0, 0].plot(x, np.sin(x))
β’ Set the title for a specific subplot.
axes[0, 0].set_title('Subplot 1')β’ Set labels for a specific subplot.
axes[0, 0].set_xlabel('X-axis')
axes[0, 0].set_ylabel('Y-axis')β’ Add a legend to a specific subplot.
axes[0, 0].legend(['Sine'])
β’ Add a main title for the entire figure.
fig.suptitle('Main Figure Title')β’ Automatically adjust subplot parameters for a tight layout.
plt.tight_layout()
β’ Share x or y axes between subplots.
fig, axes = plt.subplots(2, 1, sharex=True)
β’ Get the current Axes instance.
ax = plt.gca()
β’ Create a second y-axis that shares the x-axis.
ax2 = ax.twinx()
VI. Specialized Plots
β’ Create a contour plot.
X, Y = np.meshgrid(x, x)
Z = np.sin(X) * np.cos(Y)
plt.contour(X, Y, Z, levels=10)
β’ Create a filled contour plot.
plt.contourf(X, Y, Z)
β’ Create a stream plot for vector fields.
U, V = np.cos(X), np.sin(Y)
plt.streamplot(X, Y, U, V)
β’ Create a 3D surface plot.
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z)
#Python #Matplotlib #DataVisualization #DataScience #Plotting
βββββββββββββββ
By: @DataScienceM β¨
π€π§ LongCat-Video: Meituanβs Groundbreaking Step Toward Efficient Long Video Generation with AI
ποΈ 04 Nov 2025
π AI News & Trends
In the rapidly advancing field of generative AI, the ability to create realistic, coherent, and high-quality videos from text or images has become one of the most sought-after goals. Meituan, one of the leading technology innovators in China, has made a remarkable stride in this domain with its latest open-source model β LongCat-Video. Designed as ...
#LongCatVideo #Meituan #GenerativeAI #VideoGeneration #AIInnovation #OpenSource
ποΈ 04 Nov 2025
π AI News & Trends
In the rapidly advancing field of generative AI, the ability to create realistic, coherent, and high-quality videos from text or images has become one of the most sought-after goals. Meituan, one of the leading technology innovators in China, has made a remarkable stride in this domain with its latest open-source model β LongCat-Video. Designed as ...
#LongCatVideo #Meituan #GenerativeAI #VideoGeneration #AIInnovation #OpenSource
π‘ Top 50 Pandas Operations in Python
(Note: Examples assume the import
I. Series & DataFrame Creation
β’ Create a pandas Series from a list.
β’ Create a DataFrame from a dictionary of lists.
β’ Create a DataFrame from a list of dictionaries.
β’ Read data from a CSV file.
β’ Create a date range.
II. Data Inspection & Selection
β’ View the first 5 rows.
β’ View the last 5 rows.
β’ Get a concise summary of the DataFrame.
β’ Get descriptive statistics for numerical columns.
β’ Get the dimensions of the DataFrame (rows, columns).
β’ Get the column labels.
β’ Get the index (row labels).
β’ Select a single column.
β’ Select multiple columns.
β’ Select rows by label/index name using
β’ Select rows by integer position using
β’ Perform boolean/conditional selection.
β’ Filter rows using
III. Data Cleaning
β’ Check for missing/null values.
β’ Drop rows with any missing values.
β’ Fill missing values with a specific value.
β’ Check for duplicated rows.
β’ Drop duplicated rows.
IV. Data Manipulation & Operations
β’ Drop specified labels (columns or rows).
β’ Rename columns.
β’ Set a column as the index.
β’ Reset the index.
β’ Apply a function along an axis (e.g., per column).
β’ Apply a function element-wise to a Series.
β’ Sort by values in a column.
β’ Sort by index.
β’ Change the data type of a column.
β’ Create a new column based on a calculation.
V. Grouping & Aggregation
(Note: Examples assume the import
import pandas as pd and import numpy as np)I. Series & DataFrame Creation
β’ Create a pandas Series from a list.
s = pd.Series([1, 3, 5, np.nan, 6, 8])
β’ Create a DataFrame from a dictionary of lists.
data = {'col1': [1, 2, 3], 'col2': [4, 5, 6]}
df = pd.DataFrame(data)β’ Create a DataFrame from a list of dictionaries.
data = [{'a': 1, 'b': 2}, {'a': 5, 'b': 10, 'c': 20}]
df = pd.DataFrame(data)β’ Read data from a CSV file.
df = pd.read_csv('my_file.csv')β’ Create a date range.
dates = pd.date_range('20230101', periods=6)II. Data Inspection & Selection
β’ View the first 5 rows.
df.head()
β’ View the last 5 rows.
df.tail()
β’ Get a concise summary of the DataFrame.
df.info()
β’ Get descriptive statistics for numerical columns.
df.describe()
β’ Get the dimensions of the DataFrame (rows, columns).
df.shape
β’ Get the column labels.
df.columns
β’ Get the index (row labels).
df.index
β’ Select a single column.
df['col1'] # or df.col1
β’ Select multiple columns.
df[['col1', 'col2']]
β’ Select rows by label/index name using
.loc.df.loc[0:2, ['col1']] # Select rows 0,1,2 and column 'col1'
β’ Select rows by integer position using
.iloc.df.iloc[0:3, 0:1] # Select first 3 rows and first column
β’ Perform boolean/conditional selection.
df[df['col1'] > 2]
β’ Filter rows using
.isin().df[df['col1'].isin([1, 3])]
III. Data Cleaning
β’ Check for missing/null values.
df.isnull().sum() # Returns a Series with counts of nulls per column
β’ Drop rows with any missing values.
df.dropna()
β’ Fill missing values with a specific value.
df.fillna(value=0)
β’ Check for duplicated rows.
df.duplicated()
β’ Drop duplicated rows.
df.drop_duplicates(inplace=True)
IV. Data Manipulation & Operations
β’ Drop specified labels (columns or rows).
df.drop('col1', axis=1) # Drop a columnβ’ Rename columns.
df.rename(columns={'col1': 'new_col1_name'})β’ Set a column as the index.
df.set_index('col1')β’ Reset the index.
df.reset_index(drop=True)
β’ Apply a function along an axis (e.g., per column).
df.apply(np.cumsum)
β’ Apply a function element-wise to a Series.
df['col1'].map(lambda x: x*100)
β’ Sort by values in a column.
df.sort_values(by='col1', ascending=False)
β’ Sort by index.
df.sort_index(axis=1, ascending=False)
β’ Change the data type of a column.
df['col1'].astype('float')β’ Create a new column based on a calculation.
df['new_col'] = df['col1'] * 2
V. Grouping & Aggregation
π₯1
β’ Group data by a column.
β’ Group by a column and get the sum.
β’ Apply multiple aggregation functions at once.
β’ Get the size of each group.
β’ Get the frequency counts of unique values in a Series.
β’ Create a pivot table.
VI. Merging, Joining & Concatenating
β’ Merge two DataFrames (like a SQL join).
β’ Concatenate (stack) DataFrames along an axis.
β’ Join DataFrames on their indexes.
VII. Input & Output
β’ Write a DataFrame to a CSV file.
β’ Write a DataFrame to an Excel file.
β’ Read data from an Excel file.
β’ Read from a SQL database.
VIII. Time Series & Special Operations
β’ Use the string accessor (
β’ Use the datetime accessor (
β’ Create a rolling window calculation.
β’ Create a basic plot from a Series or DataFrame.
#Python #Pandas #DataAnalysis #DataScience #Programming
βββββββββββββββ
By: @DataScienceM β¨
df.groupby('col1')β’ Group by a column and get the sum.
df.groupby('col1').sum()β’ Apply multiple aggregation functions at once.
df.groupby('col1').agg(['mean', 'count'])β’ Get the size of each group.
df.groupby('col1').size()β’ Get the frequency counts of unique values in a Series.
df['col1'].value_counts()
β’ Create a pivot table.
pd.pivot_table(df, values='D', index=['A', 'B'], columns=['C'])
VI. Merging, Joining & Concatenating
β’ Merge two DataFrames (like a SQL join).
pd.merge(left_df, right_df, on='key_column')
β’ Concatenate (stack) DataFrames along an axis.
pd.concat([df1, df2]) # Stacks rows
β’ Join DataFrames on their indexes.
left_df.join(right_df, how='outer')
VII. Input & Output
β’ Write a DataFrame to a CSV file.
df.to_csv('output.csv', index=False)β’ Write a DataFrame to an Excel file.
df.to_excel('output.xlsx', sheet_name='Sheet1')β’ Read data from an Excel file.
pd.read_excel('input.xlsx', sheet_name='Sheet1')β’ Read from a SQL database.
pd.read_sql_query('SELECT * FROM my_table', connection_object)VIII. Time Series & Special Operations
β’ Use the string accessor (
.str) for Series operations.s.str.lower()
s.str.contains('pattern')
β’ Use the datetime accessor (
.dt) for Series operations.s.dt.year
s.dt.day_name()
β’ Create a rolling window calculation.
df['col1'].rolling(window=3).mean()
β’ Create a basic plot from a Series or DataFrame.
df['col1'].plot(kind='hist')
#Python #Pandas #DataAnalysis #DataScience #Programming
βββββββββββββββ
By: @DataScienceM β¨
β€6π1π₯1