当前位置:网站首页>Pandas(五)—— 分类数据、读取数据库
Pandas(五)—— 分类数据、读取数据库
2022-08-05 05:13:00 【share16】
Python模块 —— Pandas
Pandas(五)—— 分类数据、读取数据库
大家可以关注知乎或微信公众号的share16,我们也会同步更新此文章。
九、分类数据
9.1 cat对象
在pandas中提供了category类型,使用户能够处理分类类型的变量,将一个普通序列转换成分类变量可以使用astype方法;
import pandas as pd
df = pd.DataFrame([['A',19,120],['B',20,128],['C',19,115]],columns=['name','age','score'])
s = df.score.astype('category')
''' 属性 '''
ls1 = ['s的数据类型','类似于type','以Index类型存储','是否有序','赋予编号(取决于cat.categories中的顺序)']
ls2 = ['s.dtype','s.cat','s.cat.categories','s.cat.ordered','s.cat.codes']
print('\033[1;31m···cat对象的属性···\033[0m')
for i,j in zip(ls1,ls2):
print('{}({})的运行结果:\n{}\n'.format(j,i,eval(j)))
''' 增删改 '''
ls3 = ['增','删(若不存在,返回错误)','删除未出现在序列中的类别','改','set']
ls4 = ['s.cat.add_categories(90)','s.cat.remove_categories(115)','s.cat.remove_unused_categories()',\
's.cat.rename_categories({115:135})','s.cat.set_categories([115,120])']
print('\033[1;31m···cat对象的增删改查···\033[0m')
for i,j in zip(ls3,ls4):
print('{}({})的运行结果:\n{}\n'.format(j,i,eval(j)))


9.2 有序分类
有序类别和无序类别:可通过s.cat.as_unordered和s.cat.reorder_categories互相转化,需注意的是后者传入的参数必须是由当前序列的无序类别构成的列表,不能够增加新的类别,也不能缺少原来的类别,并且必须指定参数ordered=True,否则方法无效。
排序/大小:排序sort_index()、sort_values();大小>=、==等;
9.3 区间类别
9.3.1 利用cut和qcut进行区间构造
pd.cut(series,bins,right,labels,retbins,precision,include_lowest,duplicates,ordered)
pd.qcut(series,q,labels,retbins,precision,duplicates)
- bins:可为int/序列; q:可为int/列表(由浮点数组成),即分位数;
- labels:返回的bin的标签;默认None,还可为False/数组;若为True,则引发错误;
9.3.2 一般区间的构造
pd.Interval(left,right,closed)
- 参数left和right必须是同一类型,且要满足left <= right;
- closed:默认right,还可取值left、both、neither;
pd.IntervalIndex 对象有四类方法生成,分别是from_breaks、from_arrays、from_tuples、interval_range;
- from_breaks:类似于cut/qcut函数,区别是:cut/qcut是通过计算得到的分割点,而from_breaks是直接传入自定义的分割点;
- from_arrays:是分别传入左端点和右端点的列表,适用于有交集并且知道起点和终点的情况;
- from_tuples:传入的是起点和终点元组构成的列表;
- interval_range:由参数start、end、periods、freq构成;
十、读取数据库
10.1 连接数据库
- 导入模块 pymysql;
- 相关代码(建立连接、创建游标、执行sql查询、获取数据、关闭连接):
import pymysql
''' 1.建立连接 '''
conn = pymysql.connect(host='localhost', # 还可以是'127.0.0.1'
user='用户名',password='密码',
database='库名',port=3306,
charset='utf8')
''' 2.创建游标 '''
cur = conn.cursor()
''' 3.执行sql查询 '''
cur.execute('mysql语句') # 必须要有此句,否则data执行错误
''' 4.获取数据 '''
data = cur.fetchall()
# 此外还可为fetchmany(size)、fetchone();
# 以元组形式返回,表中每一行又是一个小元组;
# 每次更新execute中的语句时,其后面的一系列如data等,也要进行更新;
# 若要执行‘增删改更新’,要有conn.commit(),提交到数据库执行;
''' 5.关闭 '''
cur.close()
conn.close()
10.2 read_sql
- 导入模块 sqlalchemy.create_engine、pandas;
- 相关连接,如下;
import pandas as pd
from sqlalchemy import create_engine
engine = create_engine('mysql+pymysql://用户名:密码@ip:端口/库名?charset=utf8')
sql = 'mysql语句'
df = pd.read_sql(sql,engine)
df.head()
谢谢大家
边栏推荐
猜你喜欢

Qt produces 18 frames of Cupid to express his love, is it your Cupid!!!

RL reinforcement learning summary (1)

Using QR codes to solve fixed asset management challenges

OFDM Lecture 16 5 -Discrete Convolution, ISI and ICI on DMT/OFDM Systems

解决端口占用问题

类的底层机制

Flutter real machine running and simulator running

Pycharm中使用pip安装第三方库安装失败:“Non-zero exit code (2)“的解决方法

shell函数

Basic properties of binary tree + oj problem analysis
随机推荐
【过一下 17】pytorch 改写 keras
uva1325
2022 The 4th C.Easy Counting Problem (EGF+NTT)
电话溥功能
coppercam primer [6]
day9-字符串作业
【技能】长期更新
Opencv中,imag=cv2.cvtColor(imag,cv2.COLOR_BGR2GRAY) 报错:error:!_src.empty() in function ‘cv::cvtColor‘
【cesium】Load and locate 3D Tileset
Returned object not currently part of this pool
[Software Exam System Architect] Software Architecture Design ③ Domain-Specific Software Architecture (DSSA)
Matplotlib(一)—— 基础
Reverse theory knowledge 4
数据库实验五 备份与恢复
redis persistence
RDD和DataFrame和Dataset
Using QR codes to solve fixed asset management challenges
DOM and its applications
1.3 mysql批量插入数据
shell函数