Files
2026-10-02 11:10:29 +02:00

56 KiB
Executable File

Pendule Ballistique

In [1]:
import pandas as pd
import numpy as np

Moment d'inertie \Theta du pendule

In [2]:
# constantes
g = 9.81    # acceleration de la gravite

# variables

m1 = 23.25e-3  # masse balle 1
m2 = 66.00e-3  # masse balle 2
M = 196.70e-3     # masse pendule
dm = 0.01e-3  # incertitude masse
rcm1 = 275e-3   # distance centre de masse pendule
drcm1 = 1e-3  # incertitude distance centre de masse pendule
rcm2 = 279e-3
drcm2 = 1e-3
r = 295e-3     # distance d'impact
dr = 1e-3    # incertitude distance d'impact
n = 20     # nombre d'oscillations
t1 = 21.81
t2 = 21.67     # temps pour n oscillations
dt = 0.2    # incertitude temps pour n oscillations

# calcul moment d'inertie moyen pour m1 avec erreurs propagées
Theta1 = (1 / (4 * np.pi**2)) * (t1 / n)**2 * (m1 + M) * g * rcm1
dTheta1 = Theta1 * np.sqrt( (2 * dt / t1)**2 + (drcm1 / rcm1)**2 + (np.sqrt(dm**2 + dm**2) / (m1 + M))**2 )

# calcul moment d'inertie moyen pour m2 avec erreurs propagées
Theta2 = (1 / (4 * np.pi**2)) * (t2 / n)**2 * (m2 + M) * g * rcm2
dTheta2 = Theta2 * np.sqrt( (2 * dt / t2)**2 + (drcm2 / rcm2)**2 + (np.sqrt(dm**2 + dm**2) / (m2 + M))**2 )
# affichage des résultats
print(f"Moment d'inertie pour m1: Θ = {Theta1:.3f} ± {dTheta1:.4f} kg·m²")
print(f"Moment d'inertie pour m2: Θ = {Theta2:.3f} ± {dTheta2:.4f} kg·m²")
Moment d'inertie pour m1: Θ = 0.018 ± 0.0003 kg·m²
Moment d'inertie pour m2: Θ = 0.021 ± 0.0004 kg·m²

Vitesse initiale v_{0} du projectile

In [3]:
v1df = pd.DataFrame({
  'phi': np.deg2rad([25, 25, 17.5, 11.5]),
  'dphi': np.deg2rad([0.5, 0.5, 0.5, 0.5]),
  'v': [np.nan]*4,
  'dv': [np.nan]*4,
  'p': [np.nan]*4,
  'dp': [np.nan]*4,
  'L': [np.nan]*4,
  'dL': [np.nan]*4,
  'Ke': [np.nan]*4,
  'dKe': [np.nan]*4,
  'Kp': [np.nan]*4,
  'dKp': [np.nan]*4,
  'eps': [np.nan]*4,
  'deps': [np.nan]*4,
})

v2df = pd.DataFrame({
  'phi': np.deg2rad([46, 46, 33, 21]),
  'dphi': np.deg2rad([0.5, 0.5, 0.5, 0.5]),
  'v': [np.nan]*4,
  'dv': [np.nan]*4,
  'p': [np.nan]*4,
  'dp': [np.nan]*4,
  'L': [np.nan]*4,
  'dL': [np.nan]*4,
  'Ke': [np.nan]*4,
  'dKe': [np.nan]*4,
  'Kp': [np.nan]*4,
  'dKp': [np.nan]*4,
  'eps': [np.nan]*4,
  'deps': [np.nan]*4,
})

v = lambda df, m, Theta, r, rcm: (1 / (m * r)) * np.sqrt(2 * g * (m + M) * Theta * rcm * (1 - np.cos(df['phi'])))

p = lambda df, m: m * df['v']

L = lambda df, r: df['p'] * r

Ke = lambda df, m: 1 / 2 * m * df['v']**2

Kp = lambda df, m, M, rcm: (m + M) * rcm * g * (1 - np.cos(df['phi']))

eps = lambda df: df['Kp'] / df['Ke']


dv = lambda df, m, Theta, dTheta, rcm, drcm, r, dr, M, dm: np.sqrt(
  ((-1 / (m**2 * r)) * np.sqrt(2 * g * (m + M) * Theta * rcm * (1 - np.cos(df['phi']))) * dm)**2 + 
  ((-1 / (m * r**2)) * np.sqrt(2 * g * (m + M) * Theta * rcm * (1 - np.cos(df['phi']))) * dr)**2 + 
  ((np.sqrt(2 * g * (m + M) * Theta * rcm * (1 - np.cos(df['phi'])))) / (2 * m * (m + M) * r) * np.sqrt(dm**2 + dm**2))**2 + 
  ((np.sqrt(2 * g * (m + M) * Theta * rcm * (1 - np.cos(df['phi'])))) / (2 * m * r * rcm) * drcm)**2 + 
  ((np.sqrt(2 * g * (m + M) * Theta * rcm * (1 - np.cos(df['phi'])))) / (2 * m * r * Theta) * dTheta)**2 + 
  (((m + M) * Theta * rcm * g * np.sin(df['phi'])) / (2 * m * r * np.sqrt(2 * g * (m + M) * Theta * rcm * (1 - np.cos(df['phi'])))) * df['dphi'])**2 
)


dp = lambda df, m, dm: df['p'] * np.sqrt( (dm / m)**2 + (df['dv'] / df['v'])**2 )

dL = lambda df, r, dr: df['L'] * np.sqrt( (df['dp'] / df['p'])**2 + (dr / r)**2 )

dKe = lambda df, m, dm: df['Ke'] * np.sqrt( (dm / m)**2 + (2 * df['dv'] / df['v'])**2 )

dKp = lambda df, M, m, dm, rcm, drcm: np.sqrt((g * rcm * (1 - np.cos(df['phi'])) * 2 * dm * (M + m))**2+
                                              ((M + m) * g * (1 - np.cos(df['phi'])) * drcm)**2+
                                              ((M + m) * g * rcm * np.sin(df['phi']) * df['dphi'])**2 )

deps = lambda df: df['eps'] * np.sqrt( (df['dKe'] / df['Ke'])**2 + (df['dKp'] / df['Kp'])**2 )

sci = lambda x: "{:.3e}".format(x) if pd.notnull(x) else ""

v1df['v'] = v(v1df, m1, Theta1, r, rcm1)
v1df['dv'] = dv(v1df, m1, Theta1, dTheta1, rcm1, drcm1, r, dr, M, dm)
v1df['p'] = p(v1df, m1)
v1df['dp'] = dp(v1df, m1, dm)
v1df['L'] = L(v1df, r)
v1df['dL'] = dL(v1df, r, dr)
v1df['Ke'] = Ke(v1df, m1)
v1df['dKe'] = dKe(v1df, m1, dm)
v1df['Kp'] = Kp(v1df, m1, M, rcm1)
v1df['dKp'] = dKp(v1df, M, m1, dm, rcm1, drcm1)
v1df['eps'] = eps(v1df)
v1df['deps'] = deps(v1df)

v1df['ϕ + δϕ'] = v1df['phi'].map(sci) + " ± " + v1df['dphi'].map(sci)
v1df['v + δv'] = v1df['v'].map(sci) + " ± " + v1df['dv'].map(sci)
v1df['p + δp'] = v1df['p'].map(sci) + " ± " + v1df['dp'].map(sci)
v1df['L + δL'] = v1df['L'].map(sci) + " ± " + v1df['dL'].map(sci)
v1df['Ke1 + δKe1'] = v1df['Ke'].map(sci) + " ± " + v1df['dKe'].map(sci)
v1df['Ke + δKe'] = v1df['Kp'].map(sci) + " ± " + v1df['dKp'].map(sci)
v1df['ε + δε'] = v1df['eps'].map(sci) + " ± " + v1df['deps'].map(sci)

v1df.drop(columns=['phi', 'dphi', 'v', 'dv', 'p', 'dp', 'L', 'dL', 'Ke', 'dKe', 'Kp', 'dKp', 'eps', 'deps'], inplace=True)

v1df.transpose()
Out [3]:
0 1 2 3
ϕ + δϕ 4.363e-01 ± 8.727e-03 4.363e-01 ± 8.727e-03 3.054e-01 ± 8.727e-03 2.007e-01 ± 8.727e-03
v + δv 6.500e+00 ± 9.174e-02 6.500e+00 ± 9.174e-02 4.568e+00 ± 7.956e-02 3.009e+00 ± 7.194e-02
p + δp 1.511e-01 ± 2.134e-03 1.511e-01 ± 2.134e-03 1.062e-01 ± 1.850e-03 6.995e-02 ± 1.673e-03
L + δL 4.458e-02 ± 6.474e-04 4.458e-02 ± 6.474e-04 3.133e-02 ± 5.561e-04 2.064e-02 ± 4.985e-04
Ke1 + δKe1 4.911e-01 ± 1.387e-02 4.911e-01 ± 1.387e-02 2.426e-01 ± 8.451e-03 1.052e-01 ± 5.033e-03
Ke + δKe 5.559e-02 ± 2.198e-03 5.559e-02 ± 2.198e-03 2.746e-02 ± 1.560e-03 1.191e-02 ± 1.033e-03
ε + δε 1.132e-01 ± 5.499e-03 1.132e-01 ± 5.499e-03 1.132e-01 ± 7.544e-03 1.132e-01 ± 1.121e-02
In [ ]:
v2df['v'] = v(v2df, m2, Theta2, r, rcm2)
v2df['dv'] = dv(v2df, m2, Theta2, dTheta2, rcm2, drcm2, r, dr, M, dm)
v2df['p'] = p(v2df, m2)
v2df['dp'] = dp(v2df, m2, dm)
v2df['L'] = L(v2df, r)
v2df['dL'] = dL(v2df, r, dr)
v2df['Ke'] = Ke(v2df, m2)
v2df['dKe'] = dKe(v2df, m2, dm)
v2df['Kp'] = Kp(v2df, m2, M, rcm2)
v2df['dKp'] = dKp(v2df, M, m2, dm, rcm2, drcm2)
v2df['eps'] = eps(v2df)
v2df['deps'] = deps(v2df)

v2df['ϕ + δϕ'] = v2df['phi'].map(sci) + " ± " + v2df['dphi'].map(sci)
v2df['v + δv'] = v2df['v'].map(sci) + " ± " + v2df['dv'].map(sci)
v2df['p + δp'] = v2df['p'].map(sci) + " ± " + v2df['dp'].map(sci)
v2df['L + δL'] = v2df['L'].map(sci) + " ± " + v2df['dL'].map(sci)
v2df['Ke2 + δKe2'] = v2df['Ke'].map(sci) + " ± " + v2df['dKe'].map(sci)
v2df['Ke + δKe'] = v2df['Kp'].map(sci) + " ± " + v2df['dKp'].map(sci)
v2df['ε + δε'] = v2df['eps'].map(sci) + " ± " + v2df['deps'].map(sci)

v2df.drop(columns=['phi', 'dphi', 'v', 'dv', 'p', 'dp', 'L', 'dL', 'Ke', 'dKe', 'Kp', 'dKp', 'eps', 'deps'], inplace=True)

v2df.transpose()
0 1 2 3
ϕ + δϕ 8.029e-01 ± 8.727e-03 8.029e-01 ± 8.727e-03 5.760e-01 ± 8.727e-03 3.665e-01 ± 8.727e-03
v + δv 4.977e+00 ± 5.664e-02 4.977e+00 ± 5.664e-02 3.617e+00 ± 4.538e-02 2.321e+00 ± 3.608e-02
p + δp 3.284e-01 ± 3.739e-03 3.284e-01 ± 3.739e-03 2.387e-01 ± 2.995e-03 1.532e-01 ± 2.382e-03
L + δL 9.689e-02 ± 1.151e-03 9.689e-02 ± 1.151e-03 7.043e-02 ± 9.153e-04 4.519e-02 ± 7.191e-04
Ke + δKe 8.173e-01 ± 1.860e-02 8.173e-01 ± 1.860e-02 4.318e-01 ± 1.083e-02 1.778e-01 ± 5.527e-03
Kp + δKp 2.195e-01 ± 4.582e-03 2.195e-01 ± 4.582e-03 1.160e-01 ± 3.443e-03 4.776e-02 ± 2.255e-03
ε + δε 2.686e-01 ± 8.296e-03 2.686e-01 ± 8.296e-03 2.686e-01 ± 1.044e-02 2.686e-01 ± 1.519e-02
In [ ]:
v1 = v1df['v'].mean()
dv1 = np.sqrt( (v1df['dv']**2).sum() ) / len(v1df)

v2 = v2df['v'].mean()
dv2 = np.sqrt( (v2df['dv']**2).sum() ) / len(v2df)

print(f"Vitesse initiale moyenne pour m1: v0 = {v1:.3f} ± {dv1:.3f} m/s")
print(f"Vitesse initiale moyenne pour m2: v0 = {v2:.3f} ± {dv2:.3f} m/s")

Énergie du lanceur

In [30]:
k = 618
dk = 14
x1 = 0.028
dx1 = 0.0001
x2 = 0.101
dx2 = 0.0001
x0 = 0.019
dx0 = 0.0012

U = k/2 * ( (x2 - x0)**2 - (x1 - x0)**2 )
dU = np.sqrt( (1 / 2 * ((x2 - x0)**2 - (x1 - x0)**2) * dk)**2 + (k * (x2 - x0) * dx2)**2 + (-k * (x1 - x0) * dx1)**2 + (-k * (x2 - x1) * dx0)**2 )

print(f"Energie potentielle emmagasinée: U = {U:.3f} ± {dU:.3f} J")
Energie potentielle emmagasinée: U = 2.053 ± 0.072 J
In [36]:
# PowerShell
%pip install --upgrade pip
%pip install dataframe_image
Requirement already satisfied: pip in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (25.2)
Collecting pip
  Downloading pip-25.3-py3-none-any.whl.metadata (4.7 kB)
Downloading pip-25.3-py3-none-any.whl (1.8 MB)
   ---------------------------------------- 0.0/1.8 MB ? eta -:--:--
   ----------------------------- ---------- 1.3/1.8 MB 7.3 MB/s eta 0:00:01
   ---------------------------------------- 1.8/1.8 MB 6.0 MB/s  0:00:00
Installing collected packages: pip
  Attempting uninstall: pip
    Found existing installation: pip 25.2
    Uninstalling pip-25.2:
      Successfully uninstalled pip-25.2
Successfully installed pip-25.3
Note: you may need to restart the kernel to use updated packages.
Requirement already satisfied: dataframe_image in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (0.2.7)
Requirement already satisfied: pandas>=0.24 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from dataframe_image) (2.2.3)
Requirement already satisfied: nbconvert>=5 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from dataframe_image) (7.16.6)
Requirement already satisfied: aiohttp>=3.10.2 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from dataframe_image) (3.13.2)
Requirement already satisfied: requests in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from dataframe_image) (2.32.3)
Requirement already satisfied: pillow in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from dataframe_image) (11.1.0)
Requirement already satisfied: packaging in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from dataframe_image) (24.2)
Requirement already satisfied: mistune in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from dataframe_image) (3.1.4)
Requirement already satisfied: lxml in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from dataframe_image) (6.0.2)
Requirement already satisfied: beautifulsoup4 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from dataframe_image) (4.13.3)
Requirement already satisfied: cssutils in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from dataframe_image) (2.11.1)
Requirement already satisfied: playwright in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from dataframe_image) (1.55.0)
Requirement already satisfied: cssselect in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from dataframe_image) (1.3.0)
Requirement already satisfied: aiohappyeyeballs>=2.5.0 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from aiohttp>=3.10.2->dataframe_image) (2.6.1)
Requirement already satisfied: aiosignal>=1.4.0 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from aiohttp>=3.10.2->dataframe_image) (1.4.0)
Requirement already satisfied: attrs>=17.3.0 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from aiohttp>=3.10.2->dataframe_image) (25.3.0)
Requirement already satisfied: frozenlist>=1.1.1 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from aiohttp>=3.10.2->dataframe_image) (1.8.0)
Requirement already satisfied: multidict<7.0,>=4.5 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from aiohttp>=3.10.2->dataframe_image) (6.7.0)
Requirement already satisfied: propcache>=0.2.0 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from aiohttp>=3.10.2->dataframe_image) (0.4.1)
Requirement already satisfied: yarl<2.0,>=1.17.0 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from aiohttp>=3.10.2->dataframe_image) (1.22.0)
Requirement already satisfied: idna>=2.0 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from yarl<2.0,>=1.17.0->aiohttp>=3.10.2->dataframe_image) (3.10)
Requirement already satisfied: bleach!=5.0.0 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from bleach[css]!=5.0.0->nbconvert>=5->dataframe_image) (6.3.0)
Requirement already satisfied: defusedxml in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from nbconvert>=5->dataframe_image) (0.7.1)
Requirement already satisfied: jinja2>=3.0 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from nbconvert>=5->dataframe_image) (3.1.5)
Requirement already satisfied: jupyter-core>=4.7 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from nbconvert>=5->dataframe_image) (5.7.2)
Requirement already satisfied: jupyterlab-pygments in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from nbconvert>=5->dataframe_image) (0.3.0)
Requirement already satisfied: markupsafe>=2.0 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from nbconvert>=5->dataframe_image) (3.0.2)
Requirement already satisfied: nbclient>=0.5.0 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from nbconvert>=5->dataframe_image) (0.10.2)
Requirement already satisfied: nbformat>=5.7 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from nbconvert>=5->dataframe_image) (5.10.4)
Requirement already satisfied: pandocfilters>=1.4.1 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from nbconvert>=5->dataframe_image) (1.5.1)
Requirement already satisfied: pygments>=2.4.1 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from nbconvert>=5->dataframe_image) (2.19.1)
Requirement already satisfied: traitlets>=5.1 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from nbconvert>=5->dataframe_image) (5.14.3)
Requirement already satisfied: webencodings in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from bleach!=5.0.0->bleach[css]!=5.0.0->nbconvert>=5->dataframe_image) (0.5.1)
Requirement already satisfied: tinycss2<1.5,>=1.1.0 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from bleach[css]!=5.0.0->nbconvert>=5->dataframe_image) (1.4.0)
Requirement already satisfied: platformdirs>=2.5 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from jupyter-core>=4.7->nbconvert>=5->dataframe_image) (4.3.7)
Requirement already satisfied: pywin32>=300 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from jupyter-core>=4.7->nbconvert>=5->dataframe_image) (310)
Requirement already satisfied: jupyter-client>=6.1.12 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from nbclient>=0.5.0->nbconvert>=5->dataframe_image) (8.6.3)
Requirement already satisfied: python-dateutil>=2.8.2 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from jupyter-client>=6.1.12->nbclient>=0.5.0->nbconvert>=5->dataframe_image) (2.9.0.post0)
Requirement already satisfied: pyzmq>=23.0 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from jupyter-client>=6.1.12->nbclient>=0.5.0->nbconvert>=5->dataframe_image) (26.3.0)
Requirement already satisfied: tornado>=6.2 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from jupyter-client>=6.1.12->nbclient>=0.5.0->nbconvert>=5->dataframe_image) (6.4.2)
Requirement already satisfied: fastjsonschema>=2.15 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from nbformat>=5.7->nbconvert>=5->dataframe_image) (2.21.1)
Requirement already satisfied: jsonschema>=2.6 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from nbformat>=5.7->nbconvert>=5->dataframe_image) (4.23.0)
Requirement already satisfied: jsonschema-specifications>=2023.03.6 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from jsonschema>=2.6->nbformat>=5.7->nbconvert>=5->dataframe_image) (2024.10.1)
Requirement already satisfied: referencing>=0.28.4 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from jsonschema>=2.6->nbformat>=5.7->nbconvert>=5->dataframe_image) (0.36.2)
Requirement already satisfied: rpds-py>=0.7.1 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from jsonschema>=2.6->nbformat>=5.7->nbconvert>=5->dataframe_image) (0.23.1)
Requirement already satisfied: numpy>=1.26.0 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from pandas>=0.24->dataframe_image) (2.2.0)
Requirement already satisfied: pytz>=2020.1 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from pandas>=0.24->dataframe_image) (2025.1)
Requirement already satisfied: tzdata>=2022.7 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from pandas>=0.24->dataframe_image) (2025.1)
Requirement already satisfied: six>=1.5 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from python-dateutil>=2.8.2->jupyter-client>=6.1.12->nbclient>=0.5.0->nbconvert>=5->dataframe_image) (1.17.0)
Requirement already satisfied: soupsieve>1.2 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from beautifulsoup4->dataframe_image) (2.6)
Requirement already satisfied: typing-extensions>=4.0.0 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from beautifulsoup4->dataframe_image) (4.14.1)
Requirement already satisfied: more-itertools in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from cssutils->dataframe_image) (10.8.0)
Requirement already satisfied: pyee<14,>=13 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from playwright->dataframe_image) (13.0.0)
Requirement already satisfied: greenlet<4.0.0,>=3.1.1 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from playwright->dataframe_image) (3.1.1)
Requirement already satisfied: charset-normalizer<4,>=2 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from requests->dataframe_image) (3.4.1)
Requirement already satisfied: urllib3<3,>=1.21.1 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from requests->dataframe_image) (2.4.0)
Requirement already satisfied: certifi>=2017.4.17 in c:\users\romai\appdata\local\programs\python\python313\lib\site-packages (from requests->dataframe_image) (2025.6.15)
Note: you may need to restart the kernel to use updated packages.
In [37]:
import dataframe_image as dfi
styled = v1df.style \
                 .set_table_styles([{'selector': 'th', 'props': [('font-size', '12pt')]}]) \
                 .background_gradient(subset=['v'], cmap='Blues')

# export to PNG
dfi.export(styled, 'v1df.png')
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Cell In[37], line 7
      2 styled = v1df.style \
      3                  .set_table_styles([{'selector': 'th', 'props': [('font-size', '12pt')]}]) \
      4                  .background_gradient(subset=['v'], cmap='Blues')
      6 # export to PNG
----> 7 dfi.export(styled, 'v1df.png')

File c:\Users\romai\AppData\Local\Programs\Python\Python313\Lib\site-packages\dataframe_image\_pandas_accessor.py:222, in export(obj, filename, fontsize, max_rows, max_cols, table_conversion, chrome_path, dpi, use_mathjax, crop_top)
    197 """export a DataFrame as png to a file
    198 
    199 Args:
   (...)    209     crop_top: bool, optional, crop top of the generate image, default True
    210 """
    211 converter = prepare_converter(
    212     filename,
    213     fontsize,
   (...)    220     crop_top=crop_top,
    221 )
--> 222 html = generate_html(obj, filename, max_rows, max_cols)
    224 with disable_max_image_pixels():
    225     img_str = converter(html)

File c:\Users\romai\AppData\Local\Programs\Python\Python313\Lib\site-packages\dataframe_image\_pandas_accessor.py:164, in generate_html(obj, filename, max_rows, max_cols)
    161     max_cols = None
    163 if is_styler:
--> 164     html = styler2html(obj)
    165 else:
    166     html = obj.to_html(max_rows=max_rows, max_cols=max_cols, notebook=True)

File c:\Users\romai\AppData\Local\Programs\Python\Python313\Lib\site-packages\dataframe_image\pd_html.py:8, in styler2html(style)
      6 """convert dataframe and sytler to html base on different pandas version"""
      7 if version.parse(pd.__version__) >= version.parse("1.4"):
----> 8     html = style.to_html()
      9 else:
     10     html = style.render()

File c:\Users\romai\AppData\Local\Programs\Python\Python313\Lib\site-packages\pandas\io\formats\style.py:1345, in Styler.to_html(self, buf, table_uuid, table_attributes, sparse_index, sparse_columns, bold_headers, caption, max_rows, max_columns, encoding, doctype_html, exclude_styles, **kwargs)
   1342     obj.set_caption(caption)
   1344 # Build HTML string..
-> 1345 html = obj._render_html(
   1346     sparse_index=sparse_index,
   1347     sparse_columns=sparse_columns,
   1348     max_rows=max_rows,
   1349     max_cols=max_columns,
   1350     exclude_styles=exclude_styles,
   1351     encoding=encoding or get_option("styler.render.encoding"),
   1352     doctype_html=doctype_html,
   1353     **kwargs,
   1354 )
   1356 return save_to_buffer(
   1357     html, buf=buf, encoding=(encoding if buf is not None else None)
   1358 )

File c:\Users\romai\AppData\Local\Programs\Python\Python313\Lib\site-packages\pandas\io\formats\style_render.py:204, in StylerRenderer._render_html(self, sparse_index, sparse_columns, max_rows, max_cols, **kwargs)
    192 def _render_html(
    193     self,
    194     sparse_index: bool,
   (...)    198     **kwargs,
    199 ) -> str:
    200     """
    201     Renders the ``Styler`` including all applied styles to HTML.
    202     Generates a dict with necessary kwargs passed to jinja2 template.
    203     """
--> 204     d = self._render(sparse_index, sparse_columns, max_rows, max_cols, "&nbsp;")
    205     d.update(kwargs)
    206     return self.template_html.render(
    207         **d,
    208         html_table_tpl=self.template_html_table,
    209         html_style_tpl=self.template_html_style,
    210     )

File c:\Users\romai\AppData\Local\Programs\Python\Python313\Lib\site-packages\pandas\io\formats\style_render.py:161, in StylerRenderer._render(self, sparse_index, sparse_columns, max_rows, max_cols, blank)
    147 def _render(
    148     self,
    149     sparse_index: bool,
   (...)    153     blank: str = "",
    154 ):
    155     """
    156     Computes and applies styles and then generates the general render dicts.
    157 
    158     Also extends the `ctx` and `ctx_index` attributes with those of concatenated
    159     stylers for use within `_translate_latex`
    160     """
--> 161     self._compute()
    162     dxs = []
    163     ctx_len = len(self.index)

File c:\Users\romai\AppData\Local\Programs\Python\Python313\Lib\site-packages\pandas\io\formats\style_render.py:256, in StylerRenderer._compute(self)
    254 r = self
    255 for func, args, kwargs in self._todo:
--> 256     r = func(self)(*args, **kwargs)
    257 return r

File c:\Users\romai\AppData\Local\Programs\Python\Python313\Lib\site-packages\pandas\io\formats\style.py:1705, in Styler._apply(self, func, axis, subset, **kwargs)
   1703 subset = slice(None) if subset is None else subset
   1704 subset = non_reducing_slice(subset)
-> 1705 data = self.data.loc[subset]
   1706 if data.empty:
   1707     result = DataFrame()

File c:\Users\romai\AppData\Local\Programs\Python\Python313\Lib\site-packages\pandas\core\indexing.py:1184, in _LocationIndexer.__getitem__(self, key)
   1182     if self._is_scalar_access(key):
   1183         return self.obj._get_value(*key, takeable=self._takeable)
-> 1184     return self._getitem_tuple(key)
   1185 else:
   1186     # we by definition only have the 0th axis
   1187     axis = self.axis or 0

File c:\Users\romai\AppData\Local\Programs\Python\Python313\Lib\site-packages\pandas\core\indexing.py:1377, in _LocIndexer._getitem_tuple(self, tup)
   1374 if self._multi_take_opportunity(tup):
   1375     return self._multi_take(tup)
-> 1377 return self._getitem_tuple_same_dim(tup)

File c:\Users\romai\AppData\Local\Programs\Python\Python313\Lib\site-packages\pandas\core\indexing.py:1020, in _LocationIndexer._getitem_tuple_same_dim(self, tup)
   1017 if com.is_null_slice(key):
   1018     continue
-> 1020 retval = getattr(retval, self.name)._getitem_axis(key, axis=i)
   1021 # We should never have retval.ndim < self.ndim, as that should
   1022 #  be handled by the _getitem_lowerdim call above.
   1023 assert retval.ndim == self.ndim

File c:\Users\romai\AppData\Local\Programs\Python\Python313\Lib\site-packages\pandas\core\indexing.py:1420, in _LocIndexer._getitem_axis(self, key, axis)
   1417     if hasattr(key, "ndim") and key.ndim > 1:
   1418         raise ValueError("Cannot index with multidimensional key")
-> 1420     return self._getitem_iterable(key, axis=axis)
   1422 # nested tuple slicing
   1423 if is_nested_tuple(key, labels):

File c:\Users\romai\AppData\Local\Programs\Python\Python313\Lib\site-packages\pandas\core\indexing.py:1360, in _LocIndexer._getitem_iterable(self, key, axis)
   1357 self._validate_key(key, axis)
   1359 # A collection of keys
-> 1360 keyarr, indexer = self._get_listlike_indexer(key, axis)
   1361 return self.obj._reindex_with_indexers(
   1362     {axis: [keyarr, indexer]}, copy=True, allow_dups=True
   1363 )

File c:\Users\romai\AppData\Local\Programs\Python\Python313\Lib\site-packages\pandas\core\indexing.py:1558, in _LocIndexer._get_listlike_indexer(self, key, axis)
   1555 ax = self.obj._get_axis(axis)
   1556 axis_name = self.obj._get_axis_name(axis)
-> 1558 keyarr, indexer = ax._get_indexer_strict(key, axis_name)
   1560 return keyarr, indexer

File c:\Users\romai\AppData\Local\Programs\Python\Python313\Lib\site-packages\pandas\core\indexes\base.py:6200, in Index._get_indexer_strict(self, key, axis_name)
   6197 else:
   6198     keyarr, indexer, new_indexer = self._reindex_non_unique(keyarr)
-> 6200 self._raise_if_missing(keyarr, indexer, axis_name)
   6202 keyarr = self.take(indexer)
   6203 if isinstance(key, Index):
   6204     # GH 42790 - Preserve name from an Index

File c:\Users\romai\AppData\Local\Programs\Python\Python313\Lib\site-packages\pandas\core\indexes\base.py:6249, in Index._raise_if_missing(self, key, indexer, axis_name)
   6247 if nmissing:
   6248     if nmissing == len(indexer):
-> 6249         raise KeyError(f"None of [{key}] are in the [{axis_name}]")
   6251     not_found = list(ensure_index(key)[missing_mask.nonzero()[0]].unique())
   6252     raise KeyError(f"{not_found} not in index")

KeyError: "None of [Index(['v'], dtype='object')] are in the [columns]"
In [ ]: