pandas教程:Interacting with Web APIs API和数据库的交互

文章目录

  • 6.3 Interacting with Web APIs (网络相关的API交互)
  • 6.4 Interacting with Databases(与数据库的交互)

6.3 Interacting with Web APIs (网络相关的API交互)

很多网站都有公开的API,通过JSON等格式提供数据流。有很多方法可以访问这些API,这里推荐一个易用的requests包。

找到githubpandas最新的30个issues,制作一个GET HTTP request, 通过使用requests包:

import pandas as pd
import numpy as np
import requests
url = 'https://api.github.com/repos/pandas-dev/pandas/issues'
resp = requests.get(url)
resp
<Response [200]>

responsejson方法能返回一个dict,包含可以解析为python objectJSON

data = resp.json()
data[0]['title']
'Optimize data type'
data[0]
{'assignee': None,'assignees': [],'author_association': 'NONE','body': 'Hi guys, i\'m user of mysql\r\nwe have an "function" PROCEDURE ANALYSE\r\nhttps://dev.mysql.com/doc/refman/5.5/en/procedure-analyse.html\r\n\r\nit get all "dataframe" and show what\'s the best "dtype", could we do something like it in Pandas?\r\n\r\nthanks!','closed_at': None,'comments': 1,'comments_url': 'https://api.github.com/repos/pandas-dev/pandas/issues/18272/comments','created_at': '2017-11-13T22:51:32Z','events_url': 'https://api.github.com/repos/pandas-dev/pandas/issues/18272/events','html_url': 'https://github.com/pandas-dev/pandas/issues/18272','id': 273606786,'labels': [],'labels_url': 'https://api.github.com/repos/pandas-dev/pandas/issues/18272/labels{/name}','locked': False,'milestone': None,'number': 18272,'repository_url': 'https://api.github.com/repos/pandas-dev/pandas','state': 'open','title': 'Optimize data type','updated_at': '2017-11-13T22:57:27Z','url': 'https://api.github.com/repos/pandas-dev/pandas/issues/18272','user': {'avatar_url': 'https://avatars0.githubusercontent.com/u/2468782?v=4','events_url': 'https://api.github.com/users/rspadim/events{/privacy}','followers_url': 'https://api.github.com/users/rspadim/followers','following_url': 'https://api.github.com/users/rspadim/following{/other_user}','gists_url': 'https://api.github.com/users/rspadim/gists{/gist_id}','gravatar_id': '','html_url': 'https://github.com/rspadim','id': 2468782,'login': 'rspadim','organizations_url': 'https://api.github.com/users/rspadim/orgs','received_events_url': 'https://api.github.com/users/rspadim/received_events','repos_url': 'https://api.github.com/users/rspadim/repos','site_admin': False,'starred_url': 'https://api.github.com/users/rspadim/starred{/owner}{/repo}','subscriptions_url': 'https://api.github.com/users/rspadim/subscriptions','type': 'User','url': 'https://api.github.com/users/rspadim'}}

data中的每一个元素都是一个dict,这个dict就是在github上找到的issue页面上的信息。我们可以把data传给DataFrame并提取感兴趣的部分:

issues = pd.DataFrame(data, columns=['number', 'title', 'labels', 'state'])
issues
numbertitlelabelsstate
018272Optimize data type[]open
118271BUG: Series.rank(pct=True).max() != 1 for a la...[]open
218270(Series|DataFrame) datetimelike ops[]open
318268DOC: update Series.combine/DataFrame.combine d...[]open
418266DOC: updated .combine_first doc strings[{'url': 'https://api.github.com/repos/pandas-...open
518265Calling DataFrame.stack on an out-of-order col...[]open
618264cleaned up imports[{'url': 'https://api.github.com/repos/pandas-...open
718263Tslibs offsets paramd[]open
818262DEPR: let's deprecate[{'url': 'https://api.github.com/repos/pandas-...open
918258DEPR: deprecate (Sparse)Series.from_array[{'url': 'https://api.github.com/repos/pandas-...open
1018255ENH/PERF: Add cache='infer' to to_datetime[{'url': 'https://api.github.com/repos/pandas-...open
1118250Categorical.replace() unexpectedly returns non...[{'url': 'https://api.github.com/repos/pandas-...open
1218246pandas.MultiIndex.reorder_levels has no inplac...[]open
1318245TST: test tz-aware DatetimeIndex as separate m...[{'url': 'https://api.github.com/repos/pandas-...open
1418244RLS 0.21.1[{'url': 'https://api.github.com/repos/pandas-...open
1518243DEPR: deprecate .ftypes, get_ftype_counts[{'url': 'https://api.github.com/repos/pandas-...open
1618242CLN: Remove days, seconds and microseconds pro...[{'url': 'https://api.github.com/repos/pandas-...open
1718241DEPS: drop 2.7 support[{'url': 'https://api.github.com/repos/pandas-...open
1818238BUG: Fix filter method so that accepts byte an...[{'url': 'https://api.github.com/repos/pandas-...open
1918237Deprecate Series.asobject, Index.asobject, ren...[{'url': 'https://api.github.com/repos/pandas-...open
2018236df.plot() very slow compared to explicit matpl...[{'url': 'https://api.github.com/repos/pandas-...open
2118235Quarter.onOffset looks fishy[]open
2218231Reduce copying of input data on Series constru...[{'url': 'https://api.github.com/repos/pandas-...open
2318226Patch __init__ to prevent passing invalid kwds[{'url': 'https://api.github.com/repos/pandas-...open
2418222DataFrame.plot() produces incorrect legend lab...[{'url': 'https://api.github.com/repos/pandas-...open
2518220DataFrame.groupy renames columns when given a ...[]open
2618217Deprecate Index.summary[{'url': 'https://api.github.com/repos/pandas-...open
2718216Pass kwargs from read_parquet() to the underly...[{'url': 'https://api.github.com/repos/pandas-...open
2818215DOC/DEPR: ensure that @deprecated functions ha...[{'url': 'https://api.github.com/repos/pandas-...open
2918213Deprecate Series.from_array ?[{'url': 'https://api.github.com/repos/pandas-...open

6.4 Interacting with Databases(与数据库的交互)

如果在工作中,大部分数据并不会以textexcel的格式存储。最广泛使用的是SQL-based的关系型数据库(SQL Server,PostgreSQL,MySQL)。选择数据库通常取决于性能,数据整合性,实际应用的可扩展性。

读取SQLDataFrame非常直观,pandas中有一些函数能简化这个过程。举个例子,这里创建一个SQLite数据库,通过使用python内建的sqlite3 driver

import sqlite3
import pandas as pd
query = """
CREATE TABLE test
(a VARCHAR(20), b VARCHAR(20),c REAL,        d INTEGER
);"""
con = sqlite3.connect('../examples/mydata.sqlite')
con.execute(query)
<sqlite3.Cursor at 0x1049931f0>
con.commit()

然后我们插入几行数据:

data = [('Atlanta', 'Georgia', 1.25, 6),('Tallahassee', 'Florida', 2.6, 3),('Sacramento', 'California', 1.7, 5)]
stmt = "INSERT INTO test VALUES(?, ?, ?, ?)"
con.executemany(stmt, data)
<sqlite3.Cursor at 0x1049932d0>
con.commit()

大部分pythonSQL驱动(PyODBC, psycopg2, MySQLdb, pymssql, 等)返回a list of tuple,当从一个表格选择数据的时候:

cursor = con.execute('select * from test')
rows = cursor.fetchall()
rows
[('Atlanta', 'Georgia', 1.25, 6),('Tallahassee', 'Florida', 2.6, 3),('Sacramento', 'California', 1.7, 5)]

我们可以把list of tuples传递给DataFrame,但是我们也需要column names,包含cursordescription属性:

cursor.description
(('a', None, None, None, None, None, None),('b', None, None, None, None, None, None),('c', None, None, None, None, None, None),('d', None, None, None, None, None, None))
pd.DataFrame(rows, columns=[x[0] for x in cursor.description])
abcd
0AtlantaGeorgia1.256
1TallahasseeFlorida2.603
2SacramentoCalifornia1.705

我们不希望每次询问数据库的时候都重复以上步骤,这样对计算机很不好(逐步对计算机系统或文件做小改动导致大的损害)。SQLAlchemy计划是一个六星的Python SQL工具箱,它能抽象出不同SQL数据库之间的不同。pandas有一个read_sql函数,能让我们从SQLAlchemy connection从读取数据。这里我们用SQLAlchemy连接到同一个SQLite数据库,并从之前创建的表格读取数据:

import sqlalchemy as sqla
db = sqla.create_engine('sqlite:///../examples/mydata.sqlite')
pd.read_sql('select * from test', db)
abcd
0AtlantaGeorgia1.256
1TallahasseeFlorida2.603
2SacramentoCalifornia1.705

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/135012.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【Unity细节】Json序列化时出现:An item with the same key has already been added. Key:

&#x1f468;‍&#x1f4bb;个人主页&#xff1a;元宇宙-秩沅 hallo 欢迎 点赞&#x1f44d; 收藏⭐ 留言&#x1f4dd; 加关注✅! 本文由 秩沅 原创 &#x1f636;‍&#x1f32b;️收录于专栏&#xff1a;unity细节和bug &#x1f636;‍&#x1f32b;️优质专栏 ⭐【…

机器学习——CBOW负采样(纯理解)

刚从前一个坑里&#xff0c;勉强爬出来&#xff0c;又掘开另一坑 看了很多文章B站up主。。。糊里糊涂 但是我发觉&#xff0c;对于不理解的东西&#xff0c;要多看不同up主写的知识分享 书读百遍&#xff0c;其意自现&#xff0c;我是不相信的&#xff0c;容易钻牛角尖 但是&am…

前端-选中DOM定位源代码

用到的工具&#xff1a;react-dev-inspector 使用流程 根据react-dev-inspector文档进行配置 安装 yarn add --dev react-dev-inspector配置&#xff1a;在根目录下配置Inspector import { createRoot } from react-dom/client import { Inspector } from react-dev-inspe…

draw.io与项目管理——如何利用流程图工具提高项目管理效率

draw.io 是一款强大的图形绘制工具&#xff0c;用于创建各种类型的图表、流程图、组织结构图、网络图和平面设计等。它提供了丰富的绘图工具和预定义的图形库&#xff0c;使用户能够轻松创建专业水平的图形作品。 draw.io具有直观的界面和简单易用的功能&#xff0c;适合各种用…

一个拖拽内容到Word的例子

这是一个拖拽内容到Word中的例子。如视频所示&#xff1a; 从程序中的Tree这拖内容到Word中。然后 在拖拽完成后事件中&#xff0c;记录日志。 拖拽 代码如下&#xff1a; typeTForm1 class(TForm)Panel1: TPanel;TreeView1: TTreeView;GroupBox1: TGroupBox;Memo1: TMemo;D…

Webpack 的作用和工作原理是什么?

Webpack 是一个现代的静态模块打包工具&#xff0c;它的作用是将前端应用程序的各种资源&#xff08;如 JavaScript、CSS、图片等&#xff09;视为模块&#xff0c;并将它们打包成可以在浏览器中运行的静态文件。它的主要功能包括模块打包、资源优化、代码分割、加载器转换等。…

oracle_19c 安装

oracle安装部署 1、安装docker,docker-compose环境。 curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun curl -L "https://github.com/docker/compose/releases/download/1.14.0-rc2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/b…

云计算的大模型之争,亚马逊云科技落后了?

文丨智能相对论 作者丨沈浪 “OpenAI使用了Azure的智能云服务”——在过去的半年&#xff0c;这几乎成为了微软智能云最好的广告词。 正所谓“水涨船高”&#xff0c;凭借OpenAI旗下的ChatGPT在全球范围内爆发&#xff0c;微软趁势拉了一波自家的云计算业务。2023年二季度&a…

linux 安装 Anaconda3

文章目录 一、下载二、安装1.使用xftp把下载包拉到服务器上2.执行安装命令3、在安装时没有自动添加环境变量&#xff0c;这里手动设置3.1.1通过修改~/.bashrc来配置环境变量3.1.2 重新载入配置文件3.1.3 测试 一、下载 官网下载链接 二、安装 1.使用xftp把下载包拉到服务器上…

从零开始搭建微服务(二)

忘记了软件还没有装全,今天先把所有的软件装上,nacos已经装过了我们就不在装了,剩余的软件全部都是通过docker安装,我在centos7里面 1. 安装docker 安装dockeryum -y install docker开机自启 systemctl enable docker启动dockre systemctl start docker查看docker版本 doc…

css控制卡片内部的左右布局

先放效果图 纯css样式 可以根据需求进行更改 <template> <!-- 卡片盒子 --><div class"card_box "><el-card class"box-card w400" v-for"(item,index) in cardList" :key"index"><div slot"heade…

【五、http】go的http的信息提交(表单,json,上传文件)

一、post提交的几种 form表单json文件 1、提交表单 //http的postfunc requstPost(){params : make(url.Values)params.Set("name", "kaiyue")params.Set("age", "18")formDataStr : []byte(params.Encode())formDataByte : bytes.N…

学习与科学研究总决

前言 学习方法&#xff0c;做学问之道历来为人重视。 学习的一般方法 看书&#xff1a;课本阅读&#xff0c;查相关资料、论文&#xff0c;都是摄取的形式&#xff0c;是一个知识输入的过程。笔记&#xff1a;课堂笔记&#xff0c;读书笔记&#xff0c;写博客&#xff0c;发…

【python 学习】代码插桩调试

Python 代码插桩方法 文章目录 Python 代码插桩方法什么是插桩技术&#xff1f;使用插桩调试python插桩的一种实现方法 什么是插桩技术&#xff1f; 插桩技术是指在保持原有程序逻辑完整性的基础上&#xff0c;在程序中加入探针&#xff0c;通过探针来收集代码在执行过程中的信…

力扣 LCR 024. 反转链表两种解法

目录 1.解题思路Ⅰ2.代码实现Ⅰ3.解题思路Ⅱ4.代码实现Ⅱ 1.解题思路Ⅰ 利用头插法&#xff0c;遍历数组将后面的元素头插到前面的元素. 2.代码实现Ⅰ struct ListNode* reverseList(struct ListNode* head) { struct ListNode*curhead;;struct ListNode*newheadNULL;whil…

网络工程实验记录

网络工程 show ip route show running-config 第一周 相同设备使用交叉线&#xff0c;不同设备之间使用直通线 R1能ping通10.1.1.1 R2能ping通所有的 R3能ping通172.16.1.1 即路由器只能到达自身线连接出去的&#xff0c;另一端就连接不了了。 此时给R1分配静态路由 R…

单线程介绍、ECMAScript介绍、操作系统Windows、Linux 和 macOS

目录 单线程介绍ECMAScript介绍操作系统Windows、Linux 和 macOS &#x1f44d; 点赞&#xff0c;你的认可是我创作的动力&#xff01; ⭐️ 收藏&#xff0c;你的青睐是我努力的方向&#xff01; ✏️ 评论&#xff0c;你的意见是我进步的财富&#xff01; 单线程介绍 单线…

Spring Security OAuth 2.0 资源服务器— JWT

目录 一、JWT的最小依赖 二、JWT的最基本配置 1、指定授权服务器 2、初始预期&#xff08;Startup Expectations&#xff09; 3、运行时预期&#xff08;Runtime Expectations&#xff09; 三、JWT认证是如何工作的 四、直接指定授权服务器 JWK Set Uri 五、提供 audie…

kimera论文阅读

文章目录 功能构成&#xff1a;Kimera线程A. Kimera-VIO:B. Kimera-RPGO:C. Kimera-Mesher:D. Kimera-Semantics:E.调试工具 功能构成&#xff1a; Kimera包括四个关键模块: Kimera-VIO的核心是基于gtsam的VIO方法[45]&#xff0c;使用IMUpreintegration和无结构视觉因子[27]…

通达OA get_datas.php前台sql注入-可获取数据库session登入后台漏洞复现 [附POC]

文章目录 通达OA get_datas.php前台sql注入-可获取数据库session登入后台漏洞复现 [附POC]0x01 前言0x02 漏洞描述0x03 影响版本0x04 漏洞环境0x05 漏洞复现1.访问漏洞环境2.构造POC3.复现 0x06 修复建议 通达OA get_datas.php前台sql注入-可获取数据库session登入后台漏洞复现…