Pandas的数据结构
导入pandas: import pandas
import pandas as pd
from pandas import Series,DataFrame
import numpy as np
1. Series
Series是一种类似与一维数组的对象,由下面两个部分组成:
- values:一组数据(ndarray类型)
- index:相关的数据索引标签
Series的数据参数:
Series(data=None, index=None, dtype=None, name=None, copy=False, fastpath=False)
1.1 Series的创建
两种方式:
1.1.1 由列表或numpy数组创建
注意: 默认索引为0到N-1的整数型索引
示例:1
# 使用列表创建创建Series对象
Series(data=[1,2,3,4]) # 输出结果,默认第一列表示列表中每一个对应元素的索引
结果:
0 1
1 2
2 3
3 4
dtype: int64
#使用列表创建Series,可以通过设置index参数指定索引,name参数表示指定一个名称
Series(data=[1,2,3,4],index=['ds','dsa','re','gr'],name='haha')
#使用numpy创建Series
Series(data=np.arange(10,60,6)) # 使用nupay模块的range()函数创建
Series(data=np.arange(10,20,2)) # 取值区间为(10,20),步长为2
1.1.2 由字典创建:不能在使用index.但是依然存在默认索
注意:数据源必须为一维数据
dic = {
'math':100,
'English':50
}
Series(data=dic,name='qimo')
1.2 Series的索引和切片
可以使用中括号取单个索引(此时返回的是元素类型),或者中括号里一个列表取多个索引(此时返回的是一个Series类型)。
1.2.1 显示索引和隐士索引
显示索引
- 使用index中的元素作为索引值
- 使用s.loc[](推荐):注意,loc中括号中放置的一定是显示索引
注意:此时loc[] 表示的是闭区间
示例:2
使用index设置索引,此时显示的索引是自定义的,显示索引
s = Series(np.random.randint(60,100,size=(5,)),index=['a','b','c','d','e'])
s
结果:返回的是int类型
a 68
b 83
c 89
d 80
e 60
dtype: int32
通过显示索引获取指定的元素
通过显示索引进行取值
s['c']
s.loc["c"]
通过属性进行取值
s.c
结果: 这三个返回的结果都是89
隐式索引
- 使用整数作为索引值
- 使用.iloc[](推荐):iloc中的中括号中必须放置隐式索引
注意: 此时iloc[] 表示半开区间,左开右闭
对示例2进行操作;
隐式索引进行取值
s.iloc[1]
结果: 83
隐士索引取多个值
s.iloc[[1,2,3]]
结果:
b 65
c 64
d 99
dtype: int32
1.2.2 显示索引切片和隐士索引切片
显示索引切片: index和loc
隐式索引切片:整数索引值和iloc
对示例二进行操作:
显示索引切片
切取一个值
s.loc['b']
切去多个值
s.loc['a':'c']
结果:
a 85
b 65
c 64
dtype: int32
隐士索引切片
隐式索引切取一个值
s.iloc[1]
结果: 83
隐士索引取多个值
s.iloc[[1,2,3]]
结果:
b 65
c 64
d 99
dtype: int32
1.3 Series 的基本概念