pandas
一、介绍pandas
1、优点
2、pandas的数据结构
(1) DataFrame
DataFrame是一个类似于二维数组或表格(如excel)的对象,既有行索引,又有列索引
-
行索引,表明不同行,横向索引,叫index,0轴,axis=0
-
列索引,表名不同列,纵向索引,叫columns,1轴,axis=1
- DataFrame的value是ndarray类型。
DataFrame的创建
# 导入pandas
import pandas as pd
pd.DataFrame(data=None, index=None, columns=None)
pd.DataFrame(np.random.randn(2,3))
-
参数:
-
index:行标签。如果没有传入索引参数,则默认会自动创建一个从0-N的整数索引。
-
columns:列标签。如果没有传入索引参数,则默认会自动创建一个从0-N的整数索引。
pd.DataFrame(np.random.randn(2,3))
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XcW6Ziq3-1636106406524)(https://i.loli.net/2021/11/04/F1bGcLPY3kU6I5g.png)]
-
# 生成10名同学,5门功课的数据
score = np.random.randint(40, 100, (10, 5))
# 结果
array([[92, 55, 78, 50, 50],
[71, 76, 50, 48, 96],
[45, 84, 78, 51, 68],
[81, 91, 56, 54, 76],
[86, 66, 77, 67, 95],
[46, 86, 56, 61, 99],
[46, 95, 44, 46, 56],
[80, 50, 45, 65, 57],
[41, 93, 90, 41, 97],
[65, 83, 57, 57, 40]])
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QMCC30SY-1636106406526)(https://i.loli.net/2021/11/04/j1nLlpBz2my5QVN.png)]
- 增加行、列索引
# 构造行索引序列
subjects = ["语文", "数学", "英语", "政治", "体育"]
# 构造列索引序列
stu = ['同学' + str(i) for i in range(score_df.shape[0])]
# 添加行索引
data = pd.DataFrame(score, columns=subjects, index=stu)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HqD1qAvy-1636106406529)(https://i.loli.net/2021/11/04/5MjonBIVYzWUaki.png)]
DataFrame的属性
- shape
data.shape
# 结果
(10, 5)
- index
DataFrame的行索引列表
data.index
# 结果
Index(['同学0', '同学1', '同学2', '同学3', '同学4', '同学5', '同学6', '同学7', '同学8', '同学9'], dtype='object')
- columns
DataFrame的列索引列表
data.columns
# 结果
Index(['语文', '数学', '英语', '政治', '体育'], dtype='object')
- values
直接获取其中array的值
data.values
array([[92, 55, 78, 50, 50],
[71, 76, 50, 48, 96],
[45, 84, 78, 51, 68],
[81, 91, 56, 54, 76],
[86, 66, 77, 67, 95],
[46, 86, 56, 61, 99],
[46, 95, 44, 46, 56],
[80, 50, 45, 65, 57],
[41, 93, 90, 41, 97],
[65, 83, 57, 57, 40]])
- T转置
data.T
- head(5):显示前5行内容
如果不补充参数,默认5行。填入参数N则显示前N行
data.head(