- 1 Series
- 1.1 Series的创建方式
- 2、Series索引
- 2.1 通过index 指定行索引名 value查看值
- 2.2 行索引
- 2.3 切片索引
- 2.4 不连续索引
- 2.5 布尔索引
- 3 Series的基本用法
- 3.1 isnull 和 notnull 检查缺失值
- 3.2 通过索引获取数据
- 3.3 索引与数据的对应关系不被运算结果影响
- 3.4 name属性
- 总结
1 Series
提示:这里可以添加本文要记录的大概内容:
1.1 Series的创建方式1、通过列表创建
2、通过np创建
3、通过字典创建
import pandas as pd
import numpy as np
# 2.1 通过list创建
s1 = pd.Series([1,2,3,4,5])
s1
0 1
1 2
2 3
3 4
4 5
dtype: int64
-----------------------------------------------------------
# 2.2 通过数组创建
arr1 = np.arange(1,6)
print(arr1)
[1 2 3 4 5]
s2 = pd.Series(arr1)
s2
0 1
1 2
2 3
3 4
4 5
dtype: int32
---------------------------------------------------------------
# 2.3 通过字典创建 顺序不定,如果需要修改顺序,需要指定index
dict = {'name':'李宁','age':18,'class':'三班'}
s3 = pd.Series(dict,index=['name','age','class'])
s3
name 李宁
age 18
class 三班
dtype: object
2、Series索引
示例:pandas 是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的。
2.1 通过index 指定行索引名 value查看值代码如下(示例):
ser_obj = pd.Series(range(5), index = ['a', 'b', 'c', 'd', 'e']) print(ser_obj.head()) 运行结果为: a 0 b 1 c 2 d 3 e 4 dtype: int642.2 行索引
代码如下(示例):
#ser_obj[‘label’], ser_obj[pos] print(ser_obj['b']) print(ser_obj[2]) 运行结果为: 1 2
ser_obj[2:4], ser_obj[‘label1’: ’label3’]
注意,按索引名切片操作时,是包含终止索引的。
示例代码:
2.3 切片索引print(ser_obj[1:3]) print(ser_obj['b':'d']) 运行结果: b 1 c 2 dtype: int64 b 1 c 2 d 3 dtype: int64
2.4 不连续索引
ser_obj[[‘label1’, ’label2’, ‘label3’]] 示例代码: # 不连续索引 print(ser_obj[[0, 2, 4]]) print(ser_obj[['a', 'e']]) 运行结果: a 0 c 2 e 4 dtype: int64 a 0 e 4 dtype: int64
- 布尔索引
示例代码:
ser_bool = ser_obj > 2 print(ser_bool) print(ser_obj[ser_bool]) print(ser_obj[ser_obj > 2]) 运行结果: a False b False c False d True e True dtype: bool d 3 e 4 dtype: int64 d 3 e 4 dtype: int643 Series的基本用法 3.1 isnull 和 notnull 检查缺失值
s3.isnull() #判断是否为空 空就是True name False age False class False dtype: bool3.2 通过索引获取数据
通过标签或者下标进行索引
print(s3.index) print(s3.values) # 下标 s3[0] '李宁' # 标签名 s3['age'] 18 # 选取多个 s3[['name','age']] name 李宁 age 18 dtype: object # 切片 s3[:3] name 李宁 age 18 class 三班 dtype: object s3['name':'class'] name 李宁 age 18 class 三班 dtype: object #布尔索引 print(s2) s2[s2 > 3] a 1 b 2 c 3 d 4 e 5 dtype: int32 d 4 e 5 dtype: int323.3 索引与数据的对应关系不被运算结果影响
print(s2+2) print(s2>2) a 3 b 4 c 5 d 6 e 7 dtype: int32 a False b False c True d True e True dtype: bool3.4 name属性
s1.name, s1.index.name, s1.head
s2.name = 'temp' #对象名 s2.index.name = 'year' #对象索引名 s2 year a 1 b 2 c 3 d 4 e 5 Name: temp, dtype: int32 s2.head() #默认前5行 year a 1 b 2 c 3 d 4 e 5 Name: temp, dtype: int32 s2.tail(2) #尾部默认后5行 year d 4 e 5 Name: temp, dtype: int32
提示:这里对文章进行总结:
总结


