Python 
 


      ,     Python,           ,      -,     .          ,   NumPy, Pandas,  Matplotlib,         Scikit-learn.        -,   Flask, Django,    ,   Seaborn, Plotly,  Bokeh.       ,      ,       Python.     ,    Python,     ,      .





 

Python 





1.      Python



1.1.         Python

             .      ,   ,       .     Python,        ,       .

   Python    :    ,    ,             .          .

     Python   . -,         ,        ,       . -,   Python        API,     ,   .

   Python          ,    ,  , -,    . ,  NumPy  Pandas           ,   Flask  Django   -.

       Python    ,      .                  .

          ,         ,      .      ,       .

  Python           .    ,    , ,   ,       .      ,        .

       Python      . ,   TensorFlow, PyTorch  scikit-learn,      ,              ,       .

 ,       ,      ,       .              .

     Python       .    ,               .         Python,        .

  ,      ,        ,   ,        .         ,     .

 ,      ,         .      ,     ,         .

 ,         Python        ,          ,      .


1.2.  ,      

      ,       .   ,        ,         .      Python,          , -,  ,    .

          .          ,     .         ,           .

        . Python,     ,         .        ,  ,         .

         .    ,        ,         .

        ,   ,    ,       .


1.3.   

          ,          .

    

             .     ,     ,    ,        . , -      HTTP-,           .     ,        .

      

      ,    .           ,     .            ,        .        ,      .

       .               ,     ,        .     ,          .

                ,         .


1.4.       pip

           Python.  pip (Python Package Installer)      ,          Python.

       pip

1.  pip:  pip     ,    ,      :

```bash

pip install pip

```

   pip   .

2.  :    , ,  requests,   :

```bash

pip install requests

```

     requests    .

3.    :      ,     (, requirements.txt),    :

```bash

pip install -r requirements.txt

```

   

1.  :      ,  :

```bash

pip install upgrade library_name

```

      .

2.   :         , :

```bash

pip freeze local | grep -v '^\-e' |cut -d = -f 1 | xargs -n1 pip install -U

```

         ,       Python    .      :

1. `pip freeze local`:            .  `local` ,     ,     .

2. `grep -v '^\-e'`:     `grep`,   ,   `-e`.   ,        (editable mode),        .

3. `cut -d = -f 1`:          `=`     .      ,  .

4. `xargs -n1 pip install -U`:  `xargs`          `pip install -U`.  `-n1`  `xargs`      . `pip install -U`         (`-U`  "").

 ,      :

      .

  ,     .

    ( ).

     `pip install -U`,     .

3.  :    ,  :

```bash

pip uninstall library_name

```      .

    pip      ,      Python-.      ,     .


1.5     Python

Python    ,    .    ,       .        .

       

Matplotlib:        ,    . Matplotlib          .

Seaborn:   Matplotlib, Seaborn        .         .

Plotly: ,          .     .

   

Pandas:         .    ,   DataFrame,        

NumPy:           .        .

SciPy:   NumPy, SciPy   ,     , ,    .

      

Scikit-learn:     ,    , ,    .     .

TensorFlow:           .      .

PyTorch:   ,    .        .

  -

Django:       -  Python.    .

Flask:     -.    ,       .

   

SymPy:    ,       Python.

Astropy:    ,          .

         Python-.      ,       ,    .           .


1.6.     Python-

   Python-      ,       Python       .

    Python

    Python        .             .

 :             Python,    .  `venv`  ,   `virtualenv`  `conda`,       ,      .

 :              Python          .

     

  (requirements.txt):  Python-    `requirements.txt`,       ,    .        .

  :    ,   `pipenv`  `poetry`,           .     .

Semantic Versioning (SemVer):     ,      ,         .

  :       ,     .       ,  ,        .

    Python-    ,     ,       . ,    ,  ,             .

   : 

 ,     Python-,    : `requests`    HTTP-  `beautifulsoup4`   HTML-.  , ,    Python  3.7.

1.   :

```bash

python3.7 -m venv myenv

source myenv/bin/activate

```

       .         .

2.  :

```bash

pip install requests==2.26.0 beautifulsoup4==4.10.0

```

  `requirements.txt`:

```

requests==2.26.0

beautifulsoup4==4.10.0

```

          .

3.   Python:

   Python   `runtime.txt`:

```

python-3.7.*

```

4.  :

     ,      .       :

```bash

pip install upgrade requests beautifulsoup4

```

         .

5.  :

      -   .

 .       .        ,   pip  Python, npm  JavaScript,     .

  . ,    ,     .      ,         .

  .        .  ,   virtualenv ( Python)  venv,       .

 .       ,    .      , ,    ,    .

  .      . ,      ,       .

     .        .       ,       .

,            .




2.   Python



2.1. NumPy

NumPy          Python.     NumPy    ,           .               .

 :

NumPy  ,  `ndarray` ( ),        .      Python,  NumPy   ,            .        `numpy.array()`.

```python

import numpy as np

#   

arr1D = np.array([1, 2, 3])

#   

arr2D = np.array([[1, 2, 3], [4, 5, 6]])

```

   :

NumPy       ,   ,  ,     .   ,             .

```python

import numpy as np

#  

arr1 = np.array([1, 2, 3])

arr2 = np.array([4, 5, 6])

result_addition = arr1 + arr2

result_multiplication = arr1 * arr2

#  

bool_arr = arr1 > arr2

#   (ufunc)

sqrt_arr = np.sqrt(arr1)

```

  NumPy   

NumPy       .     NumPy    :

1.   :

NumPy      . ,     ,      .

```python

import numpy as np

arr1 = np.array([1, 2, 3])

arr2 = np.array([4, 5, 6])

result_addition = arr1 + arr2

print(result_addition)

```

: [5 7 9]

2.   (ufunc):

NumPy    ,       . ,       .

```python

import numpy as np

arr = np.array([1, 4, 9])

sqrt_arr = np.sqrt(arr)

print(sqrt_arr)

```

: [1. 2. 3.]

3.  :

NumPy      .   ,              NumPy.    .

```python

import numpy as np

matrix1 = np.array([[1, 2], [3, 4]])

matrix2 = np.array([[5, 6], [7, 8]])

result_matrix_product = np.dot(matrix1, matrix2)

print(result_matrix_product)

```

:

[[19 22]

[43 50]]

4. :

NumPy       ,    ,    .

```python

import numpy as np

data = np.array([1, 2, 3, 4, 5])

mean_value = np.mean(data)

std_deviation = np.std(data)

median_value = np.median(data)

print("Mean:", mean_value)

print("Standard Deviation:", std_deviation)

print("Median:", median_value)

```

:

Mean: 3.0

Standard Deviation: 1.4142135623730951

Median: 3.0

       NumPy.         ,         .


2.2. Pandas

Pandas            Python.     Pandas      DataFrame,            (  ).      DataFrame  Pandas.

1.  Pandas

 , ,      Pandas.       :

```bash

pip install pandas

```

2.  DataFrame

DataFrame      ,   , ,  NumPy, CSV-   .   .

DataFrame    ,   Pandas    Python.            (  ),           . DataFrame  Pandas       .

  DataFrame  Pandas:

1.   : DataFrame      ,       ,       ()  .

2.   :  DataFrame       .  DataFrame    ()  .

3.   :  DataFrame     ,  , ,    .

4.    : Pandas        , , ,      DataFrame.

   DataFrame:

```python

import pandas as pd

data = {'': ['', '', ''],

'': [25, 30, 22],

'': ['', '-', '']}

df = pd.DataFrame(data)

print(df)

```

   DataFrame  ,      ,      .  DataFrame    :

```

  

0  25 

1  30 -

2  22 

```

DataFrame  Pandas        ,         ,  ,   .

  :

```python

import pandas as pd

data = {'': ['', '', ''],

'': [25, 30, 22],

'': ['', '-', '']}

df = pd.DataFrame(data)

print(df)

```

 CSV-:

```python

import pandas as pd

df = pd.read_csv('.csv')

print(df)

```

CSV (Comma-Separated Values)        .   CSV     ,       ,    ,   (`,`). ,    ,     ,      (`;`)   (`\t`).

CSV-         .        ,  ,             .

 CSV-:

,,

,25,

,30,-

,22,

         ,   .   ,    ,      .

CSV-        ,   ,   (, Microsoft Excel, Google Sheets)      (, Python   Pandas).

3.    DataFrame

 :

```python

#   n  DataFrame

print(df.head())

#   n  DataFrame

print(df.tail())

```

   :

```python

#    

age = df['']

#    

row = df.loc[0]

```

 :

```python

#   

filtered_df = df[df[''] > 25]

```

  :

```python

#   

df[''] = [50000, 60000, 45000]

```

  :

```python

#     ''       

grouped_df = df.groupby('')[''].mean()

```

4.    Pandas

Pandas       . ,     :

    :

 :

```python

import pandas as pd

import matplotlib.pyplot as plt

import seaborn as sns

```

    . `pd`        Pandas. `matplotlib.pyplot`    ,  `seaborn`          .

 :

```python

data = {'': ['', '', ''],

'': [25, 30, 22],

'': ['', '-', '']}

df = pd.DataFrame(data)

```

   DataFrame   : '', ''  ''.        ,   .

  seaborn:

```python

sns.set(style="whitegrid")

```

         seaborn.     "whitegrid",       .

 :

```python

plt.figure(figsize=(8, 6))

sns.histplot(df[''], bins=20, kde=True, color='skyblue')

```

      ''  DataFrame. `figsize=(8, 6)`   . `bins=20`     . `kde=True`     . `color='skyblue'`   .

   :

```python

plt.xlabel('', fontsize=12)

plt.ylabel('', fontsize=12)

plt.title(' ', fontsize=14)

```

           

 :

```python

plt.grid(axis='y', linestyle='', alpha=0.7)

```

       .

 :

```python

plt.show()

```

 ,    .

                  Pandas, Matplotlib  Seaborn  Python.







Pandas        ,        ,     . DataFrame     ,        .   Pandas         Python.

  ,        Pandas    DataFrame    :




          ,    25 .




   DataFrame   ''  .








               .

     ,      Pandas,         .


2.3. Matplotlib

Matplotlib          Python.           .        ,      Matplotlib.

1.  

         .  :

```python

import matplotlib.pyplot as plt

#    

x = [1, 2, 3, 4, 5]

y = [10, 15, 7, 12, 9]

#   

plt.plot(x, y, marker='o', linestyle='-', color='b', label=' ')

#    

plt.xlabel('X-')

plt.ylabel('Y-')

plt.title('  ')

plt.legend() #  

#  

plt.show()

```

2. 

     . :

```python

import matplotlib.pyplot as plt

import numpy as np

#    

data = np.random.randn(1000)

#  

plt.hist(data, bins=30, color='skyblue', edgecolor='black')

#    

plt.xlabel('')

plt.ylabel('')

plt.title(' ')

#  

plt.show()

```

3.  

     . :

```python

import matplotlib.pyplot as plt

#    

sizes = [15, 30, 45, 10]

labels = [' 1', ' 2', ' 3', ' 4']

#   

plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90, colors=['skyblue', 'lightcoral', 'lightgreen', 'lightpink'])

#  

plt.title('  ')

#  

plt.show()

```

4.  

      . :

```python

import matplotlib.pyplot as plt

import numpy as np

#    

x = np.random.randn(100)

y = 2 * x + np.random.randn(100)

#   

plt.scatter(x, y, color='green', alpha=0.7)

#    

plt.xlabel('X-')

plt.ylabel('Y-')

plt.title('  ')

#  

plt.show()

```

5.  

        .

```python

import matplotlib.pyplot as plt

#    

categories = [' 1', ' 2', ' 3', ' 4']

values = [25, 40, 30, 20]

#   

plt.bar(categories, values, color=['blue', 'orange', 'green', 'red'])

#    

plt.xlabel('')

plt.ylabel('')

plt.title('  ')

#  

plt.show()

```

6.    (Boxplot)

 "  "    .

```python

import matplotlib.pyplot as plt

import numpy as np

#    

data = np.random.randn(100, 3)

#    

plt.boxplot(data, labels=[' 1', ' 2', ' 3'])

#    

plt.xlabel('')

plt.ylabel('')

plt.title('  "  "')

#  

plt.show()

```

7.  

       ,      .

```python

import matplotlib.pyplot as plt

import numpy as np

#    

data = np.random.rand(10, 10)

#   

plt.imshow(data, cmap='viridis', interpolation='nearest')

#   

plt.colorbar()

#  

plt.title('  ')

#  

plt.show()

```

       Matplotlib       . Matplotlib         ,          Python.

            .     ,        :

 :

            .

     ,      .

:

      .

      ,      .

 :

         .

        .

 :

      .

         .

 :

     .

        .

   (Boxplot):

    ,     .

           .

 :

         .

              .

            .  ,              .

 Matplotlib           Python,      Matplotlib:

1.  :

Matplotlib        : , , ,     .       .

       Matplotlib.             .



  :

    (`fig`)   (`ax`)   `plt.subplots()`.

      `ax.plot()`.




   ,   ,   .

 ,    .




    .

  ,  Matplotlib        ,    ,     .

2.    :

Matplotlib    ,          .          .

         Matplotlib.       ,       .

  :

      (`y_linear`),   (`y_quadratic`).

      (2x2)   `plt.subplots()`.

  ,       .

     `plt.tight_layout()`.

  ,  Matplotlib         ,        .





















3.   NumPy  Pandas:

Matplotlib     NumPy    Pandas,    ,    .

    Matplotlib   NumPy  Pandas.       ,  NumPy,      Matplotlib.        DataFrame   Pandas    .







  :

      NumPy      Matplotlib.

   Pandas    DataFrame       .

  ,     Matplotlib  NumPy  Pandas,          .

          Matplotlib  NumPy  Pandas       .










4.    :

,    Matplotlib,       ,   PNG, PDF, SVG  .      ,   .







      Matplotlib       .

  :

         Matplotlib.

   ,    .

    PNG, PDF  SVG   `plt.savefig()`.

   ,      (`sinus_plot.png`, `sinus_plot.pdf`, `sinus_plot.svg`),     .      ,      .

5. :

 Matplotlib      ,    .       Jupyter Notebooks.

        Matplotlib   Jupyter Notebook.       `plotly`   .

```python

import matplotlib.pyplot as plt

import numpy as np

import plotly.graph_objects as go

from IPython.display import display, HTML

#    

x = np.linspace(0, 2 * np.pi, 100)

y = np.sin(x)

#     Matplotlib

plt.plot(x, y, label='')

plt.xlabel('X-')

plt.ylabel('Y-')

plt.title('  ')

plt.legend()

#  Matplotlib      Plotly

fig = go.Figure()

fig.add_trace(go.Scatter(x=x, y=y, mode='lines', name=''))

#  

fig.update_layout(

title='  ',

xaxis=dict(title='X-'),

yaxis=dict(title='Y-'),

)

#      Jupyter Notebook

display(HTML(fig.to_html()))

```




  :

        Matplotlib.

   Plotly,      .  ,       Plotly (`pip install plotly`).

 `display(HTML(fig.to_html()))`,       Jupyter Notebook.

 ,     ,  ,        Jupyter Notebook,        .

6.   :

Matplotlib         .       ,    .

        Matplotlib.       ,        .

```python

import matplotlib.pyplot as plt

import numpy as np

#     

data = np.random.random((10, 10))

#     

colormaps = ['viridis', 'plasma', 'magma', 'inferno', 'cividis']

#      

fig, axes = plt.subplots(1, len(colormaps), figsize=(15, 3))

#       

for i, cmap in enumerate(colormaps):

im = axes[i].imshow(data, cmap=cmap)

axes[i].set_title(f' : {cmap}')

fig.colorbar(im, ax=axes[i], orientation='vertical', fraction=0.046, pad=0.04)

#   

plt.tight_layout()

#  

plt.show()

```




  :

         NumPy.

         (`viridis`, `plasma`, `magma`, `inferno`, `cividis`).

      .

       Matplotlib,     ,    .          .

 Matplotlib    .       ,   `plt.colormaps()`.

 

:      

:

            .                  .

1.  :

       .     , ,    .

2.   :

  ,        . ,      `coolwarm`        .

3.   :

  Matplotlib,   ,         .         X  Y,      .

4.  :

   ,              .

5.  ():

     ,            .

6.   :

     (, PNG  GIF)     ,   -.

7.   :

                .

      ,       ,          .

       Matplotlib    Python.               `coolwarm`. ,         .

```python

import matplotlib.pyplot as plt

import numpy as np

#   ()

latitudes = np.random.uniform(low=-90, high=90, size=(1000,))

longitudes = np.random.uniform(low=-180, high=180, size=(1000,))

temperatures = np.random.uniform(low=-20, high=40, size=(1000,))

#   

cmap = 'rainbow_r'

#   

fig, ax = plt.subplots(figsize=(12, 6))

scatter = ax.scatter(longitudes, latitudes, c=temperatures, cmap=cmap, s=50, alpha=0.7)

plt.colorbar(scatter, label='Temperature (C)')

#   (  ..)

#     ()

#   

plt.savefig('global_temperature_map.png')

plt.show()

```




       ,           .          `coolwarm`.      ,         .

7.   (Styles):

Matplotlib      ,           .         .

        Matplotlib:

```python

import numpy as np

import matplotlib.pyplot as plt

#    

x = np.linspace(0, 10, 100)

y1 = np.sin(x)

y2 = np.cos(x)

#     

plt.figure(figsize=(12, 6))

#   

plt.subplot(2, 2, 1)

plt.plot(x, y1, label='sin(x)')

plt.plot(x, y2, label='cos(x)')

plt.title('  ')

plt.legend()

#  "seaborn"

plt.subplot(2, 2, 2)

plt.style.use('seaborn')

plt.plot(x, y1, label='sin(x)')

plt.plot(x, y2, label='cos(x)')

plt.title(' "seaborn"')

plt.legend()

#  "ggplot"

plt.subplot(2, 2, 3)

plt.style.use('ggplot')

plt.plot(x, y1, label='sin(x)')

plt.plot(x, y2, label='cos(x)')

plt.title(' "ggplot"')

plt.legend()

#  "dark_background"

plt.subplot(2, 2, 4)

plt.style.use('dark_background')

plt.plot(x, y1, label='sin(x)')

plt.plot(x, y2, label='cos(x)')

plt.title(' "dark_background"')

plt.legend()

plt.tight_layout()

plt.show()

```

        :

1.    (Classic):    ,    .

2.  "seaborn":          .

3.  "ggplot":     ,    ggplot2    R.

4.  "dark_background":     ,             .




         .      ,   ,      .

8.  LaTeX:

Matplotlib   LaTeX        ,       .           ,       .

   LaTeX  Matplotlib:

```python

import numpy as np

import matplotlib.pyplot as plt

#    

x = np.linspace(0, 2 * np.pi, 100)

y = np.sin(x)

#  LaTeX     

plt.plot(x, y, label=r'$\sin(x)$')

plt.title(r'$\sin(x)$    LaTeX')

plt.xlabel(r'$x$')

plt.ylabel(r'$\sin(x)$')

#     LaTeX

plt.legend()

#  

plt.show()

```




  :

`r`    " " Python,        .

,          LaTeX.

    ,     ,    ,   ,     LaTeX.

Matplotlib       ,          ,      .

     LaTeX  :

```python

import numpy as np

import matplotlib.pyplot as plt

#    

x = np.linspace(0, 2 * np.pi, 100)

y1 = np.sin(x)

y2 = np.cos(x)

#  LaTeX    

expression = r'$f(x) = \sin(x) + \frac{\cos(2x)}{2}$'

#  

plt.figure(figsize=(8, 5))

plt.plot(x, y1, label=r'$\sin(x)$', color='blue')

plt.plot(x, y2/2, label=r'$\frac{\cos(2x)}{2}$', color='green', linestyle='')

#    LaTeX-

plt.title(f' : {expression}', fontsize=16)

#  

plt.legend()

#  

plt.grid(True)

plt.show()

```




  :

      (`sin(x)`  `cos(2x)/2`).

LaTeX-      .

     (     ).

      LaTeX-,      (`+`)   (`\frac`).

   Matplotlib       Python,   ,     .


2.4. SciPy

`SciPy`             Python.        ,   , , ,  ,    .          SciPy.


2.4.1. 

`SciPy`       ,           .        ,       ,       .

     ,   `SciPy`      ,      .     ,    ,   ,    .

        ,     ,         .         .

              ,       .

         ,       .   `SciPy`         .

              ,         .

 , `SciPy`          ,   ,    ,           .

     `minimize`:

```python

from scipy.optimize import minimize

import numpy as np

#  ,   

def objective_function(x):

return x**2 + 5*np.sin(x)

#  

initial_guess = 0

#   

result = minimize(objective_function, initial_guess)

#  

print("   :", result.x)

print("   :", result.fun)

```

:

   : [-1.11051052]

   : -3.2463942726915387


2.4.2. 

`SciPy`       ,          .        ,      . ,          ,        ,      .

   `SciPy`     ,   ,    ,    .          ,    .

              ,        .          .

   `SciPy`      ,           .        ,    .

         `SciPy`      ,    .

, `quad`      :

```python

from scipy.integrate import quad

import numpy as np

#    

def integrand(x):

return x**2

#   

result, error = quad(integrand, 0, 1)

#  

print(" :", result)

print(":", error)

```

:

 : 0.33333333333333337

: 3.700743415417189e-15


2.4.3. 

`SciPy`      ,         .            ,         .         ,              .

     `SciPy`       ,         .   ,       ,          .

  ,        ,            .                   .        ,  `SciPy`,      .

, `interp1d`      :

```python

from scipy.interpolate import interp1d

import numpy as np

import matplotlib.pyplot as plt

#  

x = np.array([1, 2, 3, 4, 5])

y = np.array([2, 0, 1, 3, 7])

#   

f = interp1d(x, y, kind='cubic')

#        

x_new = np.linspace(1, 5, 100)

y_new = f(x_new)

#  

plt.scatter(x, y, label=' ')

plt.plot(x_new, y_new, label=' ()')

plt.legend()

plt.show()

```




  `SciPy`   ,        .    ,    :


2.4.4. `scipy.signal` ( )

 `scipy.signal`   SciPy      ,          .          ,         ,          .

         ,     ,        .                .

            .       ,         .                 .

     `scipy.signal`             .        ,      .   ,   `convolve`    `spectrogram`   ,         .

```python

from scipy import signal

# :  

b, a = signal.butter(4, 0.1, 'low')

```


2.4.5. `scipy.stats` ()

 `scipy.stats`   SciPy        ,     ,   .         ,        .

        ,   t-    (ANOVA),          .             ,       .

          ,        .          ,      .

        ,     .   ,      ,        .

 `scipy.stats`       ,       ,       .  ,                .   `scipy.stats`        ,   ,     .

```python

from scipy import stats

# :     

data = stats.norm.rvs(size=1000)

```


2.4.6. `scipy.linalg` ( )

 `scipy.linalg`     SciPy          .          ,          .




  .


   .

   ,     (https://www.litres.ru/book/dzheyd-karter/python-biblioteki-70323379/chitat-onlayn/)  .

      Visa, MasterCard, Maestro,    ,   ,     ,  PayPal, WebMoney, ., QIWI ,       .


