【数据预处理】pandas读取sql数据(支持百万条读取)

主要使用两个pandas方法:

1、read_sql

函数:

pandas.read_sql(sqlconindex_col=Nonecoerce_float=Trueparams=Noneparse_dates=Nonecolumns=Nonechunksize=None)

效果:将SQL查询或数据库表读入DataFrame。

 

此功能是一个方便的包装和 (为了向后兼容)。它将根据提供的输入委派给特定的功能。SQL查询将被路由到,而数据库表名将被路由到。请注意,委派的功能可能有更多关于其功能的特定说明,此处未列出。

参数:

sql : string or SQLAlchemy Selectable (select or text object)

SQL query to be executed or a table name.

要执行的SQL查询或表名。

con : SQLAlchemy connectable (engine/connection) or database string URI

or DBAPI2 connection (fallback mode)

Using SQLAlchemy makes it possible to use any DB supported by that library. If a DBAPI2 object, only sqlite3 is supported.

或DBAPI2连接(后备模式)

使用SQLAlchemy可以使用该库支持的任何数据库。如果是DBAPI2对象,则仅支持sqlite3。

index_col : string or list of strings, optional, default: None

Column(s) to set as index(MultiIndex).

要设置为索引的列(MultiIndex)。

coerce_float : boolean, default True

Attempts to convert values of non-string, non-numeric objects (like decimal.Decimal) to floating point, useful for SQL result sets.

尝试将非字符串,非数字对象(如decimal.Decimal)的值转换为浮点,这对SQL结果集很有用。

params : list, tuple or dict, optional, default: None

List of parameters to pass to execute method. The syntax used to pass parameters is database driver dependent. Check your database driver documentation for which of the five syntax styles, described in PEP 249’s paramstyle, is supported. Eg. for psycopg2, uses %(name)s so use params={‘name’ : ‘value’}

 

parse_dates : list or dict, default: None

  • List of column names to parse as dates.

        要解析为日期的列名列表。

  • Dict of {column_name: format string} where format string is strftime compatible in case of parsing string times, or is one of (D, s, ns, ms, us) in case of parsing integer timestamps.

        在解析字符串时,格式字符串是strftime兼容的格式字符串,或者是(D、s、ns、ms、us),以防解析整型时间戳。

  • Dict of {column_name: arg dict}, where the arg dict corresponds to the keyword arguments of pandas.to_datetime() Especially useful with databases without native Datetime support, such as SQLite.

        {column_name:arg dict}的字典,其中arg dict对应于pandas.to_datetime()的关键字参数。对于没有本机Datetime支持的数据库(如SQLite)特别有用。

columns : list, default: None

List of column names to select from SQL table (only used when reading a table).

从SQL表中选择的列名列表(仅在读取表时使用)。

chunksize : int, default None

If specified, return an iterator where chunksize is the number of rows to include in each chunk.

如果指定,则返回一个迭代器,其中chunksize是要包含在每个块中的行数。

Returns:

DataFrame

 

使用案例

import pymysql
import pandas as pd

con = pymysql.connect(host="127.0.0.1",user="root",password="password",db="world")
# 读取sql
data_sql=pd.read_sql("SQL查询语句",con)
# 存储
data_sql.to_csv("test.csv")

 

2、read_sql_table

函数:

pandas.read_sql_table(table_nameconschema=Noneindex_col=Nonecoerce_float=Trueparse_dates=Nonecolumns=Nonechunksize=None)[source]

效果:将SQL数据库表读入DataFrame。

 

给定一个表名和一个SQLAlchemy可连接,返回一个DataFrame。此功能不支持DBAPI连接。

Parameters:

table_name : string

Name of SQL table in database.

数据库中SQL表的名称。

con : SQLAlchemy connectable (or database string URI)

SQLite DBAPI connection mode not supported.

不支持SQLite DBAPI连接模式。

schema : string, default None

Name of SQL schema in database to query (if database flavor supports this). Uses default schema if None (default).

要查询的数据库中的SQL模式的名称(如果数据库flavor支持此功能)。如果为None(默认值),则使用默认架构。

index_col : string or list of strings, optional, default: None

Column(s) to set as index(MultiIndex).

要设置为索引的列(MultiIndex)。

coerce_float : boolean, default True

Attempts to convert values of non-string, non-numeric objects (like decimal.Decimal) to floating point. Can result in loss of Precision.

尝试将非字符串,非数字对象(如decimal.Decimal)的值转换为浮点值。可能导致精度损失。

parse_dates : list or dict, default: None

  • List of column names to parse as dates.

        要解析为日期的列名列表。

  • Dict of {column_name: format string} where format string is strftime compatible in case of parsing string times or is one of (D, s, ns, ms, us) in case of parsing integer timestamps.

        {column_name:format string}的字典,其中格式字符串在解析字符串时间时与strftime兼容,或者在解析整        数时间戳的情况下是(D,s,ns,ms,us)之一。

  • Dict of {column_name: arg dict}, where the arg dict corresponds to the keyword arguments of pandas.to_datetime() Especially useful with databases without native Datetime support, such as SQLite.

        {column_name:arg dict}的字典,其中arg dict对应于pandas.to_datetime()的关键字参数。对于没有本机Datetime支持的数据库(如SQLite)特别有用。

columns : list, default: None

List of column names to select from SQL table

从SQL表中选择的列名列表

chunksize : int, default None

If specified, returns an iterator where chunksize is the number of rows to include in each chunk.

如果指定,则返回一个迭代器,其中chunksize是要包含在每个块中的行数。

Returns:

DataFrame

 

使用案例

import pandas as pd
import pymysql
from sqlalchemy import create_engine

con = create_engine('mysql+pymysql://user_name:password@127.0.0.1:3306/database_name')
data = pd.read_sql_table("table_name", con)
data.to_csv("table_name.csv")

 

  • 10
    点赞
  • 78
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Pandas是Python中重要的数据分析库,可用于数据预处理数据清洗和数据转换。以下是Pandas数据预处理的一些基本操作: 1. 数据读取和写入:Pandas支持多种数据文件格式,如CSV、Excel、SQL数据库等。可以使用`read_csv()`、`read_excel()`、`read_sql()`等方法读取数据,使用`to_csv()`、`to_excel()`、`to_sql()`等方法写入数据。 2. 数据缺失值处理:Pandas提供了`dropna()`、`fillna()`等方法来处理数据中的缺失值。`dropna()`方法可删除包含缺失值的行或列,`fillna()`方法可用指定的值填充缺失值。 3. 数据重复值处理:Pandas提供了`duplicated()`和`drop_duplicates()`方法来处理数据中的重复值。`duplicated()`方法可查找数据中的重复值,`drop_duplicates()`方法可删除数据中的重复值。 4. 数据类型转换Pandas支持数据类型转换为指定类型,如将字符串转换为数值类型。可以使用`astype()`方法执行类型转换。 5. 数据筛选和过滤:Pandas支持使用逻辑表达式和件表达式筛选和过滤数据。可以使用`loc[]`和`iloc[]`方法进行行列选择,使用`query()`方法执行件过滤。 6. 数据分组和聚合:Pandas支持使用`groupby()`方法将数据按照指定的列分组,然后使用聚合函数对每个分组进行计算,如`sum()`、`mean()`、`count()`等。 7. 数据合并和拼接:Pandas支持将多个数据集合并或拼接成一个数据集。可以使用`merge()`和`concat()`方法进行数据合并和拼接。 8. 数据排序和排名:Pandas支持使用`sort_values()`方法对数据进行排序,使用`rank()`方法对数据进行排名。 以上是Pandas数据预处理的一些基本操作,通过这些操作可以对数据进行有效的预处理和清洗,为后续的数据分析和建模提供良好的数据基础。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值