Pandas 系列之 Series 类型数据
本文开始正式写 Pandas 的系列文章,就从:如何在 Pandas 中创建数据开始。Pandas 中创建的数据包含两种类型:
内容导图
Series 类型
Series 是一维数组结构,它仅由 index(索引)和 value(值)构成的。
Series 的索引具有唯一性,索引既可以是数字,也可以是字符,系统会自动将它们转成一个 object 类型(pandas 中的字符类型)。
DataFrame 类型
DataFrame 是将数个 Series 按列合并而成的二维数据结构,每一列单独取出来是一个 Series ;除了拥有 index 和 value 之外,还有 column。下图中:
索引 Index:0,1,2,3…….
字段属性:fruit,number
值 value:苹果、葡萄等;200、300 等
导入库
先导入两个库:
import pandas as pdimport numpy as np
复制代码
Series 类型创建与操作
通过可迭代类型列表、元组生成
通过 python 字典生成
通过 numpy 数组生成
列表生成
通过列表的方式生成 Series 数据
s1 = pd.Series([7,8,9,10])s1
# 结果0 71 82 93 10dtype: int64
复制代码
s2 = pd.Series(list(range(1,8)))s2
# 结果0 11 22 33 44 55 66 7dtype: int64
复制代码
元组生成
下面的方法是通过元组生成 Series 数据
s3 = pd.Series((7,8,9,10,11))s3
# 结果0 71 82 93 104 11dtype: int64
复制代码
s4 = pd.Series(tuple(range(1,8))) # 从1到8,不包含8s4
# 结果0 11 22 33 44 55 66 7dtype: int64
复制代码
使用字典创建
字典的键为索引,值为 Series 结构对应的值
dic_data = {"0":"苹果", "1":"香蕉", "2":"哈密瓜","3":"橙子"}
s5 = pd.Series(dic_data)s5
# 结果0 苹果1 香蕉2 哈密瓜3 橙子dtype: object
复制代码
使用 numpy 数组
s6 = pd.Series(np.arange(3,9))s6
# 结果0 31 42 53 64 75 8dtype: int64
复制代码
指定索引(列表)
默认的索引都是从 0 开始的数值,可以在创建的时候指定每个索引
# 默认
s1 = pd.Series([7,8,9,10])s1
# 结果0 71 82 93 10dtype: int64
复制代码
s7 = pd.Series([7,8,9,10], index=["A","B","C","D"]) # 指定索引值 s7
# 结果A 7B 8C 9D 10dtype: int64
复制代码
指定索引(字典形式)
字典的键作为索引值
dic_data = {"水果1":"苹果", "水果2":"香蕉", "水果3":"哈密瓜", "水果4":"橙子" }
s8 = pd.Series(dic_data)s8
# 结果水果1 苹果水果2 香蕉水果3 哈密瓜水果4 橙子dtype: object
复制代码
查看索引值
s8
# 结果水果1 苹果水果2 香蕉水果3 哈密瓜水果4 橙子dtype: object
复制代码
s8.index # 查看索引值
# 结果Index(['水果1', '水果2', '水果3', '水果4'], dtype='object')
复制代码
查看值
s8
# 结果水果1 苹果水果2 香蕉水果3 哈密瓜水果4 橙子dtype: object
复制代码
s8.values
# 结果array(['苹果', '香蕉', '哈密瓜', '橙子'], dtype=object)
复制代码
更改索引
# 1、新索引index_new = ['one', 'two', 'three', 'four']
# 2、赋值s8.index = index_new
s8# 结果one 苹果two 香蕉three 哈密瓜four 橙子dtype: object
复制代码
查看是否存在空值
s7
# 结果A 7B 8C 9D 10dtype: int64
复制代码
s7.isnull() # 没有空值
# 结果A FalseB FalseC FalseD Falsedtype: bool
复制代码
s7.notnull()
# 结果A TrueB TrueC TrueD Truedtype: bool
复制代码
查看某个索引的值
s7
A 7B 8C 9D 10dtype: int64
复制代码
两种方式查看:
将 Series 转成字典
s_dic = s7.to_dict() # 转成字典形式s_dic
# 结果{'A': 7, 'B': 8, 'C': 9, 'D': 10}
复制代码
type(s_dic) # 结果显示为字典类型
# 结果dict
复制代码
给 Series 索引命名
s8
# 结果one 苹果two 香蕉three 哈密瓜four 橙子dtype: object
复制代码
s8.index # 原索引
Index(['one', 'two', 'three', 'four'], dtype='object')
复制代码
s8.index.name = "水果" # 索引命名s8
复制代码
结果显示为:
水果one 苹果two 香蕉three 哈密瓜four 橙子dtype: object
复制代码
Index(['one', 'two', 'three', 'four'], dtype='object', name='水果')
复制代码
修改 Series 数值
s8
# 结果为水果one 苹果two 香蕉three 哈密瓜four 橙子dtype: object
复制代码
s8["three"] = "西瓜" # 等价于s8[2] = "西瓜"
s8
复制代码
更改之后的值为:
水果one 苹果two 香蕉three 西瓜four 橙子dtype: object
复制代码
Series 结构转成 DataFrame 结构
s8
水果one 苹果two 香蕉three 西瓜four 橙子dtype: object
复制代码
在将 s8 转成 DataFrame 的过程中涉及到 3 个函数:
关于 DataFrame 的相关内容下节详细讲解,敬请期待!
扩展阅读
在之前写过的旅游攻略文章中使用 pandas 的很多知识点,可供学习:
评论