pandaspython_pandas_SeriesDataFrameMultiIndex_0">「pandas」python pandas 初步、数据结构Series、DataFrame、MultiIndex
更多内容请关注本人【pandas】专栏
【目录】
pandas_25">一、pandas简介
以numpy为基础、借力numpy模块在计算性能高的优势
基于matplotlib,能够简便画图了解结果
独特的数据结构:Series、DataFrame、MultiIndex
pandas_33">二、为什么使用pandas
- pandas能对数据进行处理,包括但不限于数据清洗、数据缺失值处理等
- 增强数据可读性——图表
- 便捷的数据处理能力——数据分析和处理
- 读取文件方便——CSV、HDF5、Excel
- 封装了matplotlib、numpy的画图和计算
pandas_41">三、pandas数据结构
- head(n)、tail(n)查看数据,默认n=5
四、Series
Series是一个类似于一维数组的数据结构,它能够保存任何类型的数据,比如整数、字符串、浮点数等,主要由一组数据和与之相关的索引两部分构成。
4.1 Series创建
- pd.Series(data=None, Index=None, dtype=None)
- data:传入的数据,可以是ndarray、list等
- index:索引,必须是唯一的,且与数据的长度相等。如果没有传入索引参数,则默认会自动创建一个从0-N-1的整数索引。
- dtype:数据的类型
4.1.1 默认索引创建Series
python">import pandas as pd
import numpy as nps1 = pd.Series(np.range(10))
print(s1)# 运行结果
0 0
1 1
2 2
3 3
4 4
5 5
dtype: int64
4.1.2 指定索引创建
python">s2 = pd.Series([12, 45, 33, 50, 66], index=['a', 'b', 'c', 'd', 'e'])
print(s2)# 运行结果
a 12
b 45
c 33
d 50
e 66
dtype: int64
4.1.3 通过字典数据创建
python">s3 = pd.Series({"age": 18, "name": "小明", "height": 180, "weight": 220})
print(s3)# 运行结果
age 18
name 小明
height 180
weight 220
dtype: objec
4.2 Series属性:index和values
- index
python">s3 = pd.Series({"age": 18, "name": "小明", "height": 180, "weight": 220})
print(s3.index)# 运行结果
Index(['age', 'name', 'height', 'weight'], dtype='object')
- values
python">s3 = pd.Series({"age": 18, "name": "小明", "height": 180, "weight": 220})
print(s3.values)# 运行结果
[18 '小明' 180 220]
4.3 Series索引获取数据:loc和iloc
- loc
- 在index上索引
- 选择index的标签数据上进行索引(即是在index上寻找相应的标签,不是下标),范围包括start和end。
python">s3 = pd.Series({"age": 18, "name": "小明", "height": 180, "weight": 220})
print(x.loc["age"])# 运行结果
18
- iloc
- 在index的位置上进行索引(即是按照普通的下标寻找),不包括end
python">s3 = pd.Series({"age": 18, "name": "小明", "height": 180, "weight": 220})
print(x.iloc[1])# 运行结果
小明
五、DataFrame
DataFrame是一个类似于二维数组或表格(如excel)的对象,既有行索引,又有列索引
行索引,表明不同行,横向索引,叫index,0轴,axis=0
列索引,表名不同列,纵向索引,叫columns,1轴,axis=1
5.1 DataFrame创建
- pd.DataFrame(data=None, index=None, columns=None)
- index:行标签。如果没有传入索引参数,则默认会自动创建一个从0-N的整数索引。
- columns:列标签。如果没有传入索引参数,则默认会自动创建一个从0-N的整数索引。
5.1.1 默认格式创建
python">d = pd.DataFrame(np.random.randint(0, 10, (2, 3)))
print(d)# 运行结果:第1行和第1列是默认索引值0 1 2
0 1 3 4
1 4 6 7
5.1.2 二维矩阵传入创建
需求:学生成绩表格的格式
python">score = np.random.randint(40, 100, (3, 5))
print(score)# 运行结果
[[42 95 44 57 63][95 67 61 41 79][69 57 83 75 46]]# 创建DataFrame
score_d = pd.DataFrame(score)
print(score_d)# 运行结果0 1 2 3 4
0 42 95 44 57 63
1 95 67 61 41 79
2 69 57 83 75 46
5.1.3 增加行列索引值
python"># 行索引
subjects = ["语文", "数学", "英语", "政治", "体育"]# 列索引
stu = ['学生_' + str(i) for i in range(score_d.shape[0])]# 添加索引
score_d = pd.DataFrame(score, columns=subjects, index=stu)
print(score_d)# 运行结果语文 数学 英语 政治 体育
学生_0 42 95 44 57 63
学生_1 95 67 61 41 79
学生_2 69 57 83 75 46
- 小插曲,设置option将输出格式对齐
python">pd.set_option('display.unicode.ambiguous_as_wide', True)
pd.set_option('display.unicode.east_asian_width', True)
python"> 语文 数学 英语 政治 体育
学生_0 57 43 77 94 62
学生_1 99 49 89 51 70
学生_2 99 92 86 52 50
5.2 DataFrame属性:shape、index、columns、values、转置T
- shape
python">print(score_d.shape)# 运行结果
(3, 5)
- index
python">print(score_d.index)# 运行结果
Index(['学生_0', '学生_1', '学生_2'], dtype='object')
- columns
python">print(score_d.columns)# 运行结果
Index(['语文', '数学', '英语', '政治', '体育'], dtype='object')
- values
python">print(score_d.values)# 运行结果
[[59 92 41 61 85][40 60 62 78 51][84 86 44 88 47]]
- 转置T
python">print(score_d.T)# 运行结果学生_0 学生_1 学生_2
语文 59 40 84
数学 92 60 86
英语 41 62 44
政治 61 78 88
体育 85 51 47
5.3 DataFrame索引设置
5.3.1 修改行列索引值
- 必须整体全部修改
- 不可以单个修改
python">stu = [f"同学_{i + 1}" for i in range(score_d.shape[0])]# 必须整体全部修改
score_d.index = stuprint(score_d.index)
# 运行结果
Index(['同学_1', '同学_2', '同学_3'], dtype='object')# 注意,下面的修改方式是错误的
# score_d.index[1] = '小明'
5.3.2 重设索引
- reset_index(drop=False, inplace=False)
- 设置新的下标索引
- drop: 默认为False,不删除原来索引,如果为True,删除原来的索引值
- inplace: 默认为False,是否返回新的DataFrame还是在原来的数据结构上修改
python">x = score_d.reset_index(inplace=True) # 由于inplace=True,则x为Noneprint(score_d)
# 运行结果index 语文 数学 英语 政治 体育
0 同学_1 65 84 74 66 84
1 同学_2 82 77 83 53 68
2 同学_3 80 63 51 94 90
5.3.3 以某列值设置为新的索引
- set_index(keys, drop=True)
- keys : 列索引名成或者列索引名称的列表
- drop : boolean, default True.当做新的索引,删除原来的列
python">df = pd.DataFrame({'month': [1, 4, 7, 10],'year': [2018, 2020, 2022, 2024],'day': [5, 13, 2, 1]})df.set_index('month', inplace=True) # 使用month作为索引
# df.set_index(['month', 'year'], inplace=True) # 多个索引,也就是MultiIndex
print(df)# 运行结果year day
month
1 2018 5
4 2020 13
7 2022 2
10 2024 1
六、MultiIndex
多级索引(层级化索引)是pandas中一个重要的特性,能让我们在一个轴(axis)上有多个index levels(索引层级)。它可以让我们在低维格式下处理高维数据。
MultiIndex是三维数据结构
python">import pandas as pd
import numpy as nppd.set_option('display.unicode.ambiguous_as_wide', True)
pd.set_option('display.unicode.east_asian_width', True)score = np.random.randint(100, size=(6, 3))
df = pd.DataFrame(score, index=[["学生1", "学生1", "学生2", "学生2", "学生3", "学生3"],["期末", "期中", "期末", "期中", "期末", "期中"]],columns=["语文", "英语", "数学"])print(df)# 运行结果语文 英语 数学
学生1 期末 0 57 67期中 42 12 20
学生2 期末 34 10 40期中 31 19 39
学生3 期末 4 57 35期中 51 22 83
6.1 pd.MultiIndex创建索引
python">score = np.random.randint(100, size=(6, 3))
names = ["同学1", "同学2", "同学3"]
period = ["期中", "期末"]
columns = ["语文", "英语", "数学"]
index = pd.MultiIndex.from_product([names, period]) # 创建索引,第一层,第二层,...
df = pd.DataFrame(score, index=index, columns=columns)print(df)