Pandas的数据结构

# 导入pandas与numpy
import pandas as pd
from pandas import Series, DataFrame
import numpy as np

一、Series

Series是一种类似与一维数组的对象,由下面两个部分组成:

  • values:一组数据(ndarray类型)
  • index:相关的数据索引标签

Series的创建

两种创建方式:

  • 由列表或numpy数组创建
  • 默认索引为0到N-1的整数型索引(隐式索引)
# 使用列表创建Series
Series(data=[1, 2, 3])
---------------------------
0 1
1 2
2 3
dtype: int64
---------------------------
  • 还可以通过设置index参数指定索引(显示索引)
s = Series(data=[1,2,3],index=['a','b','c'])
---------------------------
a 1
b 2
c 3
dtype: int64
---------------------------
s[0] # 1
s['a'] # 1
s.a # 1
---------------------------

练习:

使用多种方法创建以下Series,命名为s1:

语文 150

数学 150

英语 150

理综 300

s1 = Series(data=[150, 150, 150, 300], index=['语文', '数学', '英语', '理综'])
---------------------------
语文 150
数学 150
英语 150
理综 300
dtype: int64
---------------------------
arr = np.array([150, 150, 150, 300])
s1 = Series(data=arr, index=['语文', '数学', '英语', '理综'])

Series的索引和切片

可以使用中括号取单个索引(此时返回的是元素类型) ,或者中括号里一个列表取多个索引(此时返回的是一个Series类型)。

显式索引:

  • 使用index中的元素作为索引值
  • 使用s.loc[](推荐):注意,loc中括号中放置的一定是显式索引

注意,此时是闭区间

---------------------------
语文 150
数学 150
英语 150
理综 300
dtype: int32 s1
---------------------------
s1[3] # 300
s1[[1, 3]]
---------------------------
数学 150
理综 300
dtype: int32
---------------------------
s1[0:2]
---------------------------
语文 150
数学 150
dtype: int32
---------------------------
s1.iloc[0:2] # 行切片
---------------------------
语文 150
数学 150
dtype: int32
---------------------------

Series的基本使用

可以使用s.head(),tail()分别查看前n个和后n个值

s = Series(data=[1, 2, 2, 3, 3, 4, 5, 6, 6, 8])
s.head(2)
---------------------------
0 1
1 2
dtype: int64
---------------------------
s.tail(2)
---------------------------
8 6
9 8
dtype: int64
---------------------------
# 对Series元素进行去重
s.unique()
---------------------------
array([1, 2, 3, 4, 5, 6, 8], dtype=int64)
---------------------------

当索引没有对应的值时,可能出现缺失数据显示NaN(not a number)的情况

s1 = Series([1, 2, 3],index=['a', 'b', 'c'])
s2 = Series([1, 2, 3],index=['a', 'd', 'c'])
s = s1 + s2
---------------------------
a 2.0
b NaN
c 6.0
d NaN
dtype: float64
---------------------------
# 可以使用pd.isnull(),pd.notnull(),或s.isnull(),s.notnull()函数检测缺失数据
s[['a','b','c']]
s[[0,1,2]]
s[[True,False,True,False]] # 取出True所对应的行
---------------------------
a 2.0
c 6.0
dtype: float64
---------------------------
s.isnull() # 显示是否为null
---------------------------
a False
b True
c False
d True
dtype: bool
---------------------------
s.notnull() # 显示是否不为null
---------------------------
a True
b False
c True
d False
dtype: bool
---------------------------
# 将Series中的空值进行清洗
s[s.notnull()]
---------------------------
a 2.0
c 6.0
dtype: float64
---------------------------

Series之间的运算

  • 将索引对应的数据进行算数运算
  • 如果索引不对应,则补NaN
s1 = Series([1, 2, 3],index=['a', 'b', 'c'])
s2 = Series([1, 2, 3],index=['a', 'd', 'c'])
s = s1 + s2
---------------------------
a 2.0
b NaN
c 6.0
d NaN
dtype: float64
---------------------------

二、DataFrame

DataFrame是一个【表格型】的数据结构。DataFrame由按一定顺序排列的多列数据组成。设计初衷是将Series的使用场景从一维拓展到多维。DataFrame既有行索引,也有列索引。

  • 行索引:index
  • 列索引:columns
  • 值:values

DataFrame的创建

最常用的方法是传递一个字典来创建。DataFrame以字典的键作为每一【列】的名称,以字典的值(一个数组)作为每一列。

此外,DataFrame会自动加上每一行的索引。

使用字典创建的DataFrame后,则columns参数将不可被使用。

同Series一样,若传入的列与字典的键不匹配,则相应的值为NaN。

  • 使用ndarray创建DataFrame
df = DataFrame(data=np.random.randint(0,100,size=(3,4)),index=['a','b','c'],columns=['A','B','C','D'])
---------------------------
A B C D
a 22 32 21 50
b 33 36 17 10
c 46 92 15 50
---------------------------

DataFrame属性:values、columns、index、shape

df.values   # 所有的元素,数组
df.columns # 所有的列索引
df.index # 所有的行索引
df.shape # 形状
  • 使用字典创建DataFrame:

    创建一个表格用于展示张三,李四,王五的语文,数学的成绩
dic = {
'张三': [99, 11],
'李四': [88, 12],
'王五': [10, 100]
}
df = DataFrame(data=dic, index=['语文', '数学'])
---------------------------
张三 李四 王五
语文 99 88 10
数学 11 12 100
---------------------------

练习:

根据以下考试成绩表,创建一个DataFrame,命名为df:

    张三  李四
语文 150 0
数学 150 0
英语 150 0
理综 300 0
dic = {
'张三': [150, 150, 150, 300],
'李四': [0, 0, 0, 0]
}
df = DataFrame(data=dic, index=['语文', '数学', '英语', '理综'])

DataFrame的索引

对列进行索引

  • 通过类似字典的方式 df['q']
  • 通过属性的方式 df.q

可以将DataFrame的列获取为一个Series。返回的Series拥有原DataFrame相同的索引,且name属性也已经设置好了,就是相应的列名。

---------------------------
张三 李四
语文 150 0
数学 150 0
英语 150 0
理综 300 0
---------------------------
df['张三'] # 列索引
---------------------------
语文 150
数学 150
英语 150
理综 300
Name: 张三, dtype: int64
---------------------------

对行进行索引

  • 使用.loc[]加index来进行行索引(显式索引)
  • 使用.iloc[]加整数来进行行索引(隐式索引)

同样返回一个Series,index为原来的columns。

df.loc['语文']
df.iloc[0]
df.iloc[[0, 1]]

对元素索引的方法

  • 使用列索引
  • 使用行索引(iloc[3,1] or loc['C','q']) 行索引在前,列索引在后
df.iloc[2,1]            # 2行1列
df.loc['英语','张三'] # 英语行,张三列
df.iloc[[1,2],1] # 1,2行的1列

DataFrame的切片

【注意】

直接用中括号时:

  • 索引表示的是列索引
  • 切片表示的是行切片
df[0:2]  # 行切片

在loc和iloc中使用切片(切列) :

df.loc['B':'C','丙':'丁']

df.iloc[:, 0:1]
-------------------
张三
语文 150
数学 150
英语 150
理综 300
-------------------
  • 索引

    • df['col']:列索引,取出指定的列
    • df[[col1,col2]]:取出多列
    • df.iloc[1]:取指定的1行
    • df.loc['语文']:取指定的行
    • df.iloc[hang,lie]:取元素
  • 切片:
    • df[行切片]:切行
    • df.iloc[hang,lie]:切列

DataFrame的运算

DataFrame之间的运算

同Series一样:

  • 在运算中自动对齐不同索引的数据
  • 如果索引不对应,则补NaN
dic = {
'张三': [150, 150, 150, 300],
'李四': [0, 0, 0, 0]
}
df1 = DataFrame(data=dic, index=['语文', '数学', '英语', '理综'])
------------------- 张三 李四
语文 150 0
数学 150 0
英语 150 0
理综 300 0
-------------------
dic = {
'张三': [15, 15, 15, 30],
'李四': [60, 50, 40, 30]
}
df2 = DataFrame(data=dic, index=['语文', '数学', '英语', '理综'])
-------------------
张三 李四
语文 15 60
数学 15 50
英语 15 40
理综 30 30
-------------------
  1. 假设df1是期中考试成绩,df2是期末考试成绩,求期中期末平均值。
  2. 假设张三期中考试数学被发现作弊,要记为0分,如何实现?
  3. 李四因为举报张三作弊立功,期中考试所有科目加100分,如何实现?
  4. 后来老师发现有一道题出错了,为了安抚学生情绪,给每位学生每个科目都加10分,如何实现?
mean_score = (df1 + df2)/2
df1.loc['数学', '张三'] = 0
df1.loc[:,'李四'] += 100
df1 += 10

最新文章

  1. Android Weekly Notes Issue #222
  2. Redis五种基本数据结构
  3. 攻城狮在路上(肆)How tomcat works(二) 一个简单的servlet容器
  4. HTML笔记(六)文档类型
  5. 消除PyCharm中满屏的波浪线
  6. unity HideInInspector 默认值 坑 记录 bug
  7. vijos1603迷宫
  8. 20个linux命令行工具监视性能(上)
  9. Mac系统杂项 (持续更新)
  10. 管理支撑办公系统技术架构选型对照讨论(J2EE与SOA对照)
  11. Angular-搜索框及价格上下限
  12. c#中缓存的使用
  13. C# - 引用类型
  14. DevExpress ASP.NET Core Controls 2019发展蓝图(No.4)
  15. 转码器ffmpeg安装
  16. CSS样式学习-3、轮廓、伪类/元素、display-flex布局
  17. table垂直居中
  18. .babelrc文件的一些简单的配置
  19. Professional layer CodeForces - 1103D (状压,gcd)
  20. golang web框架 beego 学习 (三) beego获取参数

热门文章

  1. 机器学习-K-means聚类及算法实现(基于R语言)
  2. MT41J256M16HA-125 原厂订购 现货销售
  3. ffmpeg参数
  4. MongoDb学习 自定义配置mongodb连接
  5. 【leetcode】1034. Coloring A Border
  6. OC—类的设计和NSString
  7. Dubbo学习-7-dubbo配置文件优先级
  8. SPFA的两个优化
  9. [CSP-S模拟测试]:神炎皇(数学)
  10. bootstrap 前端框架学习笔记