zoukankan      html  css  js  c++  java
  • pandas从数据库读取数据

    因为本周有一个是需要使用pandos做一个数据分析的需求,所以在这里做一下记录。

    Python中用Pandas进行数据分析,最常用的就是Dataframe数据结构,
    这里我们主要介绍Pandas如何读取数据到Dataframe。

    1. Pandas读取Mysql数据要读取Mysql中的数据,首先要安装Mysqldb包。假设我数据库安装在本地,用户名位myusername,密码为mypassword,要读取mydb数据库中的数据,那么对应的代码如下:
    import pandas as pd
    import MySQLdb
    mysql_cn= MySQLdb.connect(host='localhost', port=3306,user='myusername', passwd='mypassword', db='mydb')
    df = pd.read_sql('select * from test;', con=mysql_cn)    
    mysql_cn.close()
    

    上面的代码读取了test表中所有的数据到df中,而df的数据结构为Dataframe。

    1. Pandas读取csv文件数据Pandas读取csv文件中的数据要简单的多,不用额外安装程序包,假设我们要读取test.csv中的数据, 对应的代码如下:
    df = pd.read_csv(loggerfile, header=None, sep=',')
    

    header=None表示没有头部,sep=’,’表示字段之间的分隔符为逗号。


    关于对数据分析的思考
    这里的需求是根据本周的数据得到对比上周的数据的环比趋势等信息。但是由于数据一直都是增量更新到数据库,所以需要用需要使用时间字段控制查询范围,
    这里补充几个关于数据库查询的sql
    查询今天的数据
    select * from tj where to_days(now()) = to_days(tjsj)
    查询z昨天的数据
    select * from tj where to_days(now()) - to_days(tjsj) = 1
    查询本周数据
    select * from tj where tjsj >= subdate(curdate(),date_format(curdate(),'%w')-1) and tjsj <= subdate(curdate(),date_format(curdate(),'%w')-7)
    查询上周数据
    select * from tj where tjsj >= subdate(curdate(),date_format(curdate(),'%w')+6) and tjsj <= subdate(curdate(),date_format(curdate(),'%w')-0)

    需求完成阶段如下:
    1、使用数据库查询sql,查询出符合条件的上周数据。 查询创建时间是上周,或者更新时间是上周的数据。
    2、使用数据库查询sql,查询出符合条件的本周数据。 查询创建时间是本周,或者更新时间是本周的数据。
    3、进行数据分析的工作,得到想要的数据。分析1、2 得到的数据,并且进行运算。
    计划本工作两日完成。

  • 相关阅读:
    bzoj5137 [Usaco2017 Dec]Standing Out from the Herd
    bzoj2434 [Noi2011]阿狸的打字机
    【20181024T2】小C的序列【GCD性质+链表】
    【20181024T3】小C的宿舍【分治】
    【20181024T1】小C的数组【二分+dp】
    【20181023T2】行星通道计划【二维BIT】
    【20181023T1】战争【反向并查集】
    【20181020T1】蛋糕
    【20181019T2】硬币【矩阵快速幂优化DP】
    【20181019T3】比特战争【最小生成树思想】
  • 原文地址:https://www.cnblogs.com/wangcc7/p/12556292.html
Copyright © 2011-2022 走看看