栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

【数据准备和特征工程】1-2感知数据库中的数据

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【数据准备和特征工程】1-2感知数据库中的数据

pymysql读取数据
import pymysql
mydb = pymysql.connect(host="localhost",    # ①
                       user='root',
                       password='********',
                       db="books",
                      )
cursor = mydb.cursor()    # ②
sql = "select * from mybooks"    # ③
cursor.execute(sql)    # ④
datas = cursor.fetchall()    # ⑤
for data in datas:
    print(data)
(1, 'Learn Python', 'phei')
(2, 'Django', 'phei')
(3, 'Data Analysis', 'phei')
(4, 'Machine Learning', 'PHEI')
(5, '数据可视化案例', 'gitchat')
(6, '零基础入手Python', 'gitchat')

文章目录
  • pymysql读取数据
  • pandas读取数据
  • 将数据保存到数据库
    • 先准备要放入数据库的数据
    • 将数据存入数据库
    • 看看存放结果

pandas读取数据
import pandas as pd

df = pd.read_sql_query(sql, con=mydb, index_col='id')
df
D:CSAppsanacondaanaconda3envsailibsite-packagespandasiosql.py:761: UserWarning: pandas only support SQLAlchemy connectable(engine/connection) ordatabase string URI or sqlite3 DBAPI2 connectionother DBAPI2 objects are not tested, please consider using SQLAlchemy
  warnings.warn(
nameauthor
id
1Learn Pythonphei
2Djangophei
3Data Analysisphei
4Machine LearningPHEI
5数据可视化案例gitchat
6零基础入手Pythongitchat
将数据保存到数据库 先准备要放入数据库的数据
df = pd.read_csv("../data/HospInfo.csv")
df.info()

RangeIndex: 4812 entries, 0 to 4811
Data columns (total 29 columns):
 #   Column                                                         Non-Null Count  Dtype 
---  ------                                                         --------------  ----- 
 0   Provider ID                                                    4812 non-null   int64 
 1   Hospital Name                                                  4812 non-null   object
 2   Address                                                        4812 non-null   object
 3   City                                                           4812 non-null   object
 4   State                                                          4812 non-null   object
 5   ZIP Code                                                       4812 non-null   int64 
 6   County Name                                                    4797 non-null   object
 7   Phone Number                                                   4812 non-null   int64 
 8   Hospital Type                                                  4812 non-null   object
 9   Hospital Ownership                                             4812 non-null   object
 10  Emergency Services                                             4812 non-null   bool  
 11  Meets criteria for meaningful use of EHRs                      4668 non-null   object
 12  Hospital overall rating                                        4812 non-null   object
 13  Hospital overall rating footnote                               1398 non-null   object
 14  Mortality national comparison                                  4812 non-null   object
 15  Mortality national comparison footnote                         1352 non-null   object
 16  Safety of care national comparison                             4812 non-null   object
 17  Safety of care national comparison footnote                    2168 non-null   object
 18  Readmission national comparison                                4812 non-null   object
 19  Readmission national comparison footnote                       1017 non-null   object
 20  Patient experience national comparison                         4812 non-null   object
 21  Patient experience national comparison footnote                1369 non-null   object
 22  Effectiveness of care national comparison                      4812 non-null   object
 23  Effectiveness of care national comparison footnote             1202 non-null   object
 24  Timeliness of care national comparison                         4812 non-null   object
 25  Timeliness of care national comparison footnote                1266 non-null   object
 26  Efficient use of medical imaging national comparison           4812 non-null   object
 27  Efficient use of medical imaging national comparison footnote  2033 non-null   object
 28  Location                                                       4812 non-null   object
dtypes: bool(1), int64(3), object(25)
memory usage: 1.0+ MB
将数据存入数据库
import pymysql
import sqlalchemy
from sqlalchemy import create_engine
connect_info = 'mysql+pymysql://{}:{}@{}:{}/{}'.format('root',
                                                       '********',
                                                       'localhost',
                                                       3306,
                                                       'pymysql')
engine = create_engine(connect_info)
df.to_sql('hosp_info',engine,if_exists='replace')
# if_exists='',replace:删除表,重新创建保存数据(覆盖数据),append:向表中追加数据
4812
看看存放结果
conn = pymysql.connect(host="localhost",    # ①
                       user='root',
                       password='********',
                       db="pymysql")
cursor = conn.cursor()
sql = "select * from hosp_info"


df = pd.read_sql(sql, conn, index_col='Provider ID')
df.head()
D:CSAppsanacondaanaconda3envsailibsite-packagespandasiosql.py:761: UserWarning: pandas only support SQLAlchemy connectable(engine/connection) ordatabase string URI or sqlite3 DBAPI2 connectionother DBAPI2 objects are not tested, please consider using SQLAlchemy
  warnings.warn(
indexHospital NameAddressCityStateZIP CodeCounty NamePhone NumberHospital TypeHospital Ownership...Readmission national comparison footnotePatient experience national comparisonPatient experience national comparison footnoteEffectiveness of care national comparisonEffectiveness of care national comparison footnoteTimeliness of care national comparisonTimeliness of care national comparison footnoteEfficient use of medical imaging national comparisonEfficient use of medical imaging national comparison footnoteLocation
Provider ID
100050MARSHALL MEDICAL CENTER SOUTH2505 U S HIGHWAY 431 NORTHBOAZAL35957MARSHALL2565938310Acute Care HospitalsGovernment - Hospital District or Authority...NoneSame as the national averageNoneSame as the national averageNoneAbove the national averageNoneBelow the national averageNone2505 U S HIGHWAY 431 NORTHnBOAZ, ALn
100121DEKALB REGIONAL MEDICAL CENTER200 MED CENTER DRIVEFORT PAYNEAL35968DE KALB2568453150Acute Care HospitalsProprietary...NoneSame as the national averageNoneSame as the national averageNoneAbove the national averageNoneSame as the national averageNone200 MED CENTER DRIVEnFORT PAYNE, ALn
100322WEDOWEE HOSPITAL209 NORTH MAIN STREETWEDOWEEAL36278RANDOLPH2563572111Acute Care HospitalsGovernment - Hospital District or Authority...NoneNot AvailableResults are not available for this reporting p...Same as the national averageNoneSame as the national averageNoneNot AvailableResults are not available for this reporting p...209 NORTH MAIN STREETnWEDOWEE, ALn
100953HALE COUNTY HOSPITAL508 GREEN STREETGREENSBOROAL36744HALE3346243024Acute Care HospitalsGovernment - Local...Results are not available for this reporting p...Not AvailableResults are not available for this reporting p...Below the national averageNoneSame as the national averageNoneNot AvailableResults are not available for this reporting p...508 GREEN STREETnGREENSBORO, ALn
101314CRESTWOOD MEDICAL CENTERONE HOSPITAL DR SEHUNTSVILLEAL35801MADISON2568823100Acute Care HospitalsProprietary...NoneSame as the national averageNoneSame as the national averageNoneSame as the national averageNoneSame as the national averageNoneONE HOSPITAL DR SEnHUNTSVILLE, ALn

5 rows × 29 columns

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1026373.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号