Работа с базой данных с помощью Pandas

Опубликовано: 27 Марта, 2022

Выполнение различных операций с данными, сохраненными в SQL, может привести к выполнению очень сложных запросов, которые нелегко написать. Поэтому, чтобы упростить эту задачу, часто бывает полезно выполнять ее с помощью панд, которые специально созданы для предварительной обработки данных и являются более простыми и удобными, чем SQL.

Могут быть случаи, когда иногда данные хранятся в SQL, и мы хотим получить эти данные из SQL в python, а затем выполнить операции с помощью pandas. Итак, давайте посмотрим, как мы можем взаимодействовать с базами данных SQL с помощью pandas.

Это база данных, с которой мы будем работать
диабет_данные

Примечание. Предполагая, что данные хранятся в sqlite3.

Чтение данных

# import the libraries
import sqlite3
import pandas as pd
  
# create a connection
con = sqlite3.connect("Diabetes.db")
  
# read data from SQL to pandas dataframe.
data = pd.read_sql_query("Select * from Diabetes;", con)
  
# show top 5 rows
data.head()

Выход

Basic operation

  • Slicing of rows
    We can perform slicing operations to get the desired number of rows from within a given range.
    With the help of slicing, we can perform various operations only on the specific subset of the data
    # read the data from sql to pandas dataframe.
    data = pd.read_sql_query("Select * from Diabetes;", con)
      
    # slicing the number of rows 
    df1 = data[10:15]
    df1

    Output

  • Selecting specific columns
    To select a particular column or to select number of columns from the dataframe for further processing of data.
    # read the data from sql to
    # pandas dataframe.
    data = pd.read_sql_query("Select * from Diabetes;", con)
      
    # selecting specific columns.
    df2 = data.loc[:, ["Glucose", "BloodPressure"]].head()
    df2

    Output:



  • Summarize the data
    In order to get insights from data, we must have a statistical summary of data. To display a statistical summary of the data such as mean, median, mode, std etc. We perform the following operation
    # read the data from sql 
    # to pandas dataframe.
    data = pd.read_sql_query("Select * from Diabetes;", con)
      
    # summarize the data
    data.describe()

    Output:

  • Sort data with respect to a column
    For sorting the dataframe with respect to a given column values
    # read the data from sql 
    # to pandas dataframe.
    data = pd.read_sql_query("Select * from Diabetes;", con)
      
    # sort data with respect 
    # to particular column.
    data.sort_values(by ="Age").head()

    Output:

  • Display mean of each column
    To Display the mean of every column of the dataframe.
    # read the data from sql 
    # to pandas dataframe.
    data = pd.read_sql_query("Select * from Diabetes;", con)
      
    # count number of rows and columns
    data.mean()

    Output:

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course